search

Home  >  Q&A  >  body text

What is JavaScript garbage collection?

<p>What is JavaScript garbage collection? For web programmers, understanding the importance of JavaScript garbage collection is important in order to write better code. </p>
P粉334721359P粉334721359469 days ago572

reply all(2)I'll reply

  • P粉033429162

    P粉0334291622023-08-18 09:23:54

    When it comes to DOM objects, be aware of circular references:

    Memory Leak Patterns in JavaScript

    Remember that memory can only be reclaimed when there are no active references to the object. This is a common pitfall with closures and event handlers, as some JS engines don't check the variables actually referenced in the inner function, and will just keep all the local variables of the enclosing function.

    Here is a simple example:

    function init() {
        var bigString = new Array(1000).join('xxx');
        var foo = document.getElementById('foo');
        foo.onclick = function() {
            // 即使`bigString`在任何地方都没有被引用,这可能会创建对`bigString`的闭包!
        };
    }

    A naive JS implementation cannot collect bigString when the event handler exists. There are several ways to solve this problem, such as setting bigString = null at the end of init() (delete does not work for local variables and function parameters: delete removes a property from an object while the variable object is inaccessible - ES5 in strict mode will even throw a ReferenceError if you try to delete a local variable!).

    I recommend trying to avoid unnecessary closures if you care about memory consumption.

    reply
    0
  • P粉547170972

    P粉5471709722023-08-18 00:17:21

    Eric Lippert wrote a detailed blog post some time ago that talks about this topic (plus comparing it to VBScript ). More precisely, he wrote about JScript, which is Microsoft's own implementation of ECMAScript, albeit very similar to JavaScript. I guess you can assume that most of the behavior is the same in Internet Explorer's JavaScript engine. Of course, the specific implementation will vary from browser to browser, but I suspect you can apply some common principles to other browsers.

    Quoted from this page:

    The main purpose of garbage collection is so that programmers don't have to worry about memory management of the objects they create and use, although of course sometimes it's unavoidable - it's always beneficial to have at least a general understanding of how garbage collection works.

    Historical Note: An earlier version of the answer had an incorrect reference to the delete operator. In JavaScript, the delete operator deletes a property from an object, which is completely different from delete in C/C.

    reply
    0
  • Cancelreply