javascript - Do local variables inside of a loop get garbage collected? - Stack Overflow

I'm wondering if it is more efficient to place any vars referenced within a loop, outside of the l

I'm wondering if it is more efficient to place any vars referenced within a loop, outside of the loop - or can they get garbage collected like vars inside of a function?

var obj = {key:'val'};
for(var i=0; i<10; i++){
    console.log(obj);
}

or

for(var i=0; i<10; i++){
    var obj = {key:'val'};
    console.log(obj);
}

I tried to run some memory test in my browser's profiler but still couldn't tell which method was better.

I'm wondering if it is more efficient to place any vars referenced within a loop, outside of the loop - or can they get garbage collected like vars inside of a function?

var obj = {key:'val'};
for(var i=0; i<10; i++){
    console.log(obj);
}

or

for(var i=0; i<10; i++){
    var obj = {key:'val'};
    console.log(obj);
}

I tried to run some memory test in my browser's profiler but still couldn't tell which method was better.

Share Improve this question asked Oct 11, 2011 at 2:16 George HessGeorge Hess 6891 gold badge8 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

var is function scoped, not blocked scoped, so it does not matter whether they appear inside the loop or not. What is the scope of variables in JavaScript? explains this distinction.

The next version of JavaScript will have let-scoped variables and the value stored in those would bee collectible at the end of a loop body run if declared inside the loop.

Neither will get garbage collected until the variables go out of scope. Scope in Javascript is introduced by functions. A loop construct has no influence on scope whatsoever.

As far as garbage collection, what the other answers say should be true, the browser handles the garbage collection and it doesn't matter if the variable is declared internally, or externally, to a loop.

As for efficiency, your code would be a little more optimized to declare the variable prior to the loop.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745346237a4623555.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信