Is it good practice to set variables to null when they are no longer needed?

前端 未结 4 1977
一生所求
一生所求 2020-12-05 09:32

I have seen javascript values set to null at the end of a function. Is this done to reduce memory usage or just to prevent accidental u

4条回答
  •  失恋的感觉
    2020-12-05 10:23

    There was an issue with iE and circular references involving DOM elements. This was usually created when attaching listeners as follows:

    function doStuff() {
       var el = document.getElementById('someID');
       el.onclick = function() {
         // has closure to el
       };
    
       // remove reference to element
       el = null;
    }
    

    When doStuff ia called, the anonymous function attached to the element has a closure back to the element - a circular reference. In older versions of IE this caused a memory leak so the solution was to set el to null (or anything other than el) to break the circular reference after the assignment to el.onclick.

    The second reason to use it is similar - if a function has a closure that keeps a reference a large object that might otherwise be garbage collected, then it may be useful to remove the reference so that the object can be cleaned up:

    var someFunction = (function() {
      var x = reallyBigObject;
      // do stuff that uses reallyBigObject
    
      // Remove reference to reallyBigObject if it's no longer required
      x = null;
    
      return function() {
        // closure to x is unavoidable, but reference to reallyBigObject isn't required
      }
    }());
    

    So if the function returned to someFunction doesn't actually need to reference reallyBigObject, then the reference can be removed so the closure doesn't keep it from being garbage collected unnecessarily.

    Note that you can't prevent the closure to variables in scope, but you can modify their values.

    This stuff usually isn't much of an issue unless you are keeping pages open for a long time and doing lots of AJAX and adding and removing lots of DOM nodes. But it's probably a good habit to remove references to objects in closures where they aren't needed.

提交回复
热议问题