javascript - js memory leak problem
黄舟
黄舟 2017-05-19 10:42:35
0
4
712
   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?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(4)
给我你的怀抱

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

仅有的幸福

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.

世界只因有你

What is a memory leak?

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

巴扎黑

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template