循环内的局部变量会被垃圾回收吗? [英] Do local variables inside of a loop get garbage collected?

查看:135
本文介绍了循环内的局部变量会被垃圾回收吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将所有引用的var放在循环之外,在循环之外是否更有效-还是像函数内的var一样收集垃圾?

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);
}

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.

推荐答案

var是函数作用域的,而不是阻塞作用域的,因此它们是否出现在循环内无关紧要. JavaScript中变量的范围是什么?解释了这种区别.

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.

JavaScript的下一版本将具有 let范围如果在循环内声明变量,则存储在变量中的值将在循环主体运行结束时变为可收集的.

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.

这篇关于循环内的局部变量会被垃圾回收吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆