ES6 const是否影响垃圾收集? [英] Does ES6 const affect garbage collection?

查看:375
本文介绍了ES6 const是否影响垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kyle Simpson的新标题中,您不知道JS:ES6及其以外的,我发现以下代码段:


警告将对象或数组定义为常量意味着在该常量的词法范围消失之前,该值将无法进行垃圾回收,因为对值的引用永远不会被取消设置。这可能是可取的,但如果不是您的意图,请小心!


(摘录自:辛普森,凯尔你不要知道JS:ES6& Beyond。O'Reilly Media,Inc.,2015-06-02。iBooks。
本资料可能受版权保护。)



据我所知,他并没有扩张,而Google上的10分钟没有任何变化。这是真的吗?如果是这样,对价值的引用永远不会被解除是什么意思??我已经习惯了声明不会因为 const 而变化的变量,这是一个真正具体的性能/内存条款的坏习惯吗?

解决方案

不,没有性能影响。本说明书是指通过取消设置变量来帮助垃圾收集器(这很少需要)的做法:

  { 
let x = makeHeavyObject();
window.onclick = function(){
// this *可能会关闭`x`,即使不需要它
};
x = null; //所以我们更好地清除它
}

这显然是不可能的,如果你已将 x 声明为 const



的变量(超出范围时)不受此影响。但是,如果垃圾收集器拧紧,常数将始终保持初始化的值,并防止垃圾收集,而正常变量可能不会再持有。


In Kyle Simpson's new title, You don't know JS: ES6 and beyond, I find the following snippet:

WARNING Assigning an object or array as a constant means that value will not be able to be garbage collected until that constant’s lexical scope goes away, as the reference to the value can never be unset. That may be desirable, but be careful if it’s not your intent!

(Excerpt From: Simpson, Kyle. "You Don’t Know JS: ES6 & Beyond." O'Reilly Media, Inc., 2015-06-02. iBooks. This material may be protected by copyright.)

As far as I can see, he doesn't expand on this, and 10 minutes on Google turns up nothing. Is this true, and if so, what does "the reference to the value can never be unset" mean exactly? I have got into the habit of declaring variables that won't be changed as const, is this a bad habit in real concrete performance/memory terms?

解决方案

No, there are no performance implications. This note refers to the practise of helping the garbage collector (which is rarely enough needed) by "unsetting" the variable:

{
    let x = makeHeavyObject();
    window.onclick = function() {
        // this *might* close over `x` even when it doesn't need it
    };
    x = null; // so we better clear it
}

This is obviously not possibly to do if you had declared x as a const.

The lifetime of the variable (when it goes out of scope) is not affected by this. But if the garbage collector screws up, a constant will always hold the value it was initialised with, and prevent that from being garbage-collected as well, while a normal variable might no more hold it.

这篇关于ES6 const是否影响垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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