Do local variables inside of a loop get garbage collected?

邮差的信 提交于 2020-01-05 08:14:50

问题


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.


回答1:


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 become collectible at the end of a loop body run if declared inside the loop.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7720740/do-local-variables-inside-of-a-loop-get-garbage-collected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!