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?
给我你的怀抱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
,因为js
garbage collection mechanism to execute periodically, find out the variables that are no longer used, and then release the memory occupied by them.
Garbage collection
仅有的幸福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.
世界只因有你2017-05-19 10:44:35
What is a memory leak?
This will cause an execution error. . . . . .
巴扎黑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