循环内的局部变量会被垃圾收集吗?
我想知道将循环内引用的任何变量放在循环外是否更有效 - 或者它们可以像函数内的变量一样被垃圾收集吗?
var obj = {key:'val'};
for(var i=0; i<10; i++){
console.log(obj);
}
或者
for(var i=0; i<10; i++){
var obj = {key:'val'};
console.log(obj);
}
我尝试在浏览器的分析器中运行一些内存测试,但仍然无法判断哪种方法更好。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
var
是函数作用域,而不是阻塞作用域,因此它们是否出现在循环内并不重要。 JavaScript 中变量的作用域是什么? 解释了这种区别。JavaScript 的下一个版本将具有
let
-scoped< /a> 如果在循环内声明,变量和存储在其中的值将在循环体运行结束时变为可收集的。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.在变量超出范围之前,两者都不会被垃圾回收。 Javascript 中的作用域是通过函数引入的。循环结构对范围没有任何影响。
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.