Home  >  Q&A  >  body text

javascript - js memory leak problem

   var user = { name: 'tom', age: 20, gender: 'male' }
   var test = document.getElementById('test');
       test.onclick = function() {
           test.innerHTML = user.name;
       }
   user = null; // 释放对象
   

I encountered an interview question like this recently. Is there any memory leak in this paragraph? If so, could you please tell me why and how to eliminate the memory leak?

黄舟黄舟2730 days ago697

reply all(4)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-19 10:44:35

    Memory leakSimply put, the allocated memory cannot be used or recycled until the browser process ends.

    For the circular reference problemjust eliminate the reference directly, set the test=null,因为jsgarbage collection mechanism to execute periodically, find out the variables that are no longer used, and then release the memory occupied by them.
    Garbage collection

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-19 10:44:35

    The principle is as shown in the picture below. Your test is elem in the picture. It refers to a dom element and adds an event handler to the dom element. However, the event processing function refers to the test in the external scope, so it is as follows: It becomes a circular reference.

    What will appear to be a memory leak is actually the test rather than the user. Clearing the reference to the external test can destroy this circular reference.

    In fact, these will not be a problem in modern browsers due to the use of the mark-sweep algorithm. In old browsers, the garbage collection algorithm will only cause memory leaks due to references, that is, the circular reference makes the object unavailable and cannot be garbage Recycle.

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-19 10:44:35

    What is a memory leak?

    This will cause an execution error. . . . . .

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-19 10:44:35

    Definitely, it’s included in the CVTE interview questions. Because the reference to user.name is retained in the click event, it will still be leaked.
    As for how to eliminate the problem, the only thing I can think of is to directly dereference it as mentioned above

    reply
    0
  • Cancelreply