admin管理员组文章数量:1420907
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 badges3 Answers
Reset to default 6var
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.
本文标签: javascriptDo local variables inside of a loop get garbage collectedStack Overflow
版权声明:本文标题:javascript - Do local variables inside of a loop get garbage collected? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745346236a2654490.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论