简体   繁体   English

如何在Javascript(Node.js)中为垃圾收集标记“新”对象

[英]How to mark a “new” object for garbage collection in Javascript (Node.js)

If I can't avoid using the "new" keyword in my Node.js app, how can I efficiently mark the object for garbage collection? 如果无法避免在Node.js应用程序中使用“ new”关键字,如何有效地将对象标记为垃圾回收? I create a new object with a fairly high level constructor (by that, I mean new myObj() actually creates several new Something() objects deeper down in the process. 我用一个相当高级的构造函数创建了一个新对象(这意味着, new myObj()实际上在过程的更深处创建了几个new Something()对象。

Let's say my constructor looks a little like the following: 假设我的构造函数看起来像下面的样子:

function User(name, age) {
    this.something = x;
    this.greet = function() { return "hello"; };
    this.somethingElse = new OtherThing();
    return this;
}

Then I create a new User within another function: 然后,我在另一个函数中创建一个新User

function createUserAndGreet(name, age) {
    var user1 = new User(name, age);
    user1.greet();

    // now I don't need user1 anymore
}

(btw, I know this code sucks but I think it gets my point across) (顺便说一句,我知道这段代码很烂,但是我认为这很清楚)

After I have got him to greet, how can I then get rid of him and free up the memory he occupied? 在我向他打招呼之后,我该如何摆脱他并释放他的记忆呢?

So if I just set user1 to null with user1 = null; 因此,如果我只是将user1设置为null,而user1 = null; after I'm finished with him, will he be gone forever and GC will come and clean him up? 我和他吃完饭后,他会永远消失吗,GC会来清理他吗? Will that also delete the new OtherThing() that was created? 这还会删除创建的new OtherThing()吗? Or is there something else I need to do? 还是我需要做些其他事情? I hear that using new is notorious for memory leaks so I just want to know if there's a way around this. 我听说使用new会导致内存泄漏而臭名昭著,所以我只想知道是否可以解决此问题。

The GC takes care of everything that is not referenced. GC会处理所有未引用的内容。 Your code is "GC-Compatible" as is, because after the call to createUserAndGreet() , all references are destroyed. 您的代码按原样是“ GC兼容的”,因为在调用createUserAndGreet() ,所有引用都将被销毁。

The only things you have to care about regarding GC is what is attached directly to the Window object (globals), these will never be collected. 关于GC,您唯一需要关心的是直接附加到Window对象(全局变量)的对象,这些对象将永远不会被收集。 Your two variables are scoped inside createUserAndGreet() and this scope is destroyed when the function call ends. 您的两个变量的作用域位于createUserAndGreet()并且在函数调用结束时会破坏此作用域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM