javascript new 关键字和内存泄漏? [英] javascript new keyword and memory leaks?
问题描述
let x = new MyClass();
...[more code]
let x = new MyClass();
MyClass 的第一个实例会自动被垃圾回收吗?或者我是否需要在第二次赋值之前显式 x = null
或类似的东西,以避免内存泄漏?
Will the first instance of MyClass get garbaged collected automatically? Or do I need to explicitly x = null
or something like that before the second assignment, in order to avoid a memory leak?
推荐答案
JavScript 的内存是自动管理的,因此被视为无法访问"的对象由 垃圾收集器.
JavScript's memory is managed automatically, so objects that are deemed "unreachable" are collected by the garbage collector.
在您提供的示例中,存储在 x
中的对象将被垃圾收集,只要它不能从您的代码的其他部分访问(即,如果您将它放在全局范围内...[more code]
行,对象不会被收集,因为它仍然可以访问).
In the example you provided, the object stored in x
will be garbage-collected so long as it isn't reachable from other parts of your code (i.e. if you placed it in global scope in the ...[more code]
lines, the object would not be collected as it is still reachable).
大多数情况下,您不必担心 JavaScript 中的显式内存管理,但是了解其重要的常见情况很重要(请参阅 4 种常见泄漏).
Most of the time, you don't have to worry about explicit memory management in JavaScript, however it is important to know common cases where it does matter (see 4 common leaks).
作为一个实际例子,在大多数前端框架/库中,销毁由应用程序的短期组件创建的 setInterval
很重要(即当倒计时时钟发生时销毁倒计时时钟的间隔)已从 DOM 中删除),因为这些间隔中的闭包可能会阻止对象被收集.
As a practical example, in most front-end frameworks/libraries, it's important to destroy setInterval
s created by short-lived components of your app (i.e. destroying a countdown clock's interval when that countdown clock has been removed from the DOM) as the closure in these intervals could prevent objects from being collected.
这篇关于javascript new 关键字和内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!