In JavaScript, because garbage collection is automatic, people may be less aware of this when coding. But the fact is, some webapp in the use of a period of time, there will be a cotton phenomenon, especially those single page applications, including WebView mode of mobile phone app. This phenomenon is not apparent in the traditional "click-Refresh" type of page, since the page is refreshed, all garbage objects that have not been reclaimed will be purged, but in a single page application, if there is no manual browser refresh button, then a very small memory leak, as the page stay time increases, The cumulative leakage will be more and more, the feeling on the phone is more obvious.
So here's a discussion about how memory leaks happen and how to avoid them.
To get to the point, generally there are two ways of garbage collection mechanism, one is "reference count", when an object is referenced in the number of times 0 o'clock, the object can be reclaimed, another is "Mark cleanup", when an object can no longer be accessed, mark the object, and the next GC event occurs, the objects are cleared. Since 2012, all modern browsers have been based on "tag cleanup" recycling algorithms, so if you need to be compatible with older browsers, you may need to do more. The timing of the GC is determined by the JS engine, and what needs to be known is that when the GC is in place, the main thread will be blocked, which can be seen by the Chrome Timeline tool, at least over Ms.
Chrome Devtools-timeline
You can easily see the execution of garbage collection events in Chrome. To open the Chrome Timeline, just tick "Memory" and select the second one on the left View.
Then click the dot below the magnifying glass, when Chrome will start recording memory allocation, drawing and other events, and so you open a page, such as Baidu Bar, and then click the dot (now should be red), you will see a blue line. Different pages, but there is almost always a sudden drop in the place, such as the 1200 in the picture below the left side, click it, you can display the GC event at the bottom of the time, and how much memory it reclaimed.
If you see the blue Line of your site is on the rise, in the continuous GC, memory is still rising, it is very likely that there is a memory leak, need to check the code.
Reference count
The problem here is "circular reference", if the property of object A refers to B, and B's properties refer to a, because the engine is recycled only if the variable has a reference number of 0, where a and b reference times are at least 1, so the two variables cannot be recycled even if they are running out of functions.
function foo () {var a = {},
B = {};
a.attr = b;
B.attr = A;
}
Foo ();
The reality may be this:
function foo () {var text = document.getElementById (' Input-text ');
Text.onfocus = function () {
text.value = ';
}
foo ();
This means that when the cursor is moved to the input box, the original contents are emptied. Considering the text variable and the anonymous function inside foo, the Onfocus property of the text refers to the anonymous function, which refers to the text variable (the loop), so that when Foo executes, the two objects cannot be reclaimed because the reference count is greater than 0.
In this case, you just have to empty the text variable at the end of Foo.
Text = null;
If you use Chrome to run this example, you will see the blue line or to the initial height, because the chrome is based on the "tag clear" algorithm to reclaim memory, so there is no "circular reference" problem.
Mark Clear
For tag cleanup, imagine a tree in which every page has a root, and whenever a function executes, a node is generated. Naturally, nested function calls will have child nodes. In general (without closures), when the function finishes, the internal variables are not accessible by other code, so it is marked as "inaccessible." GC, the JS engine unifies all of these state objects for recycling.
Introduces two concepts. Shallow Size, which represents the memory occupied by the object itself. Retained size, which represents the amount of memory that can be obtained after the object is disposed. What do you mean? For example, the green #3 on the map, the green area is shallow size. After the #3 is released, the #4 and #5 are also released, so the retained size is the total amount of #3, #4, #5.
In the "tag cleanup" algorithm, the difficulty is how to determine that an object is already "inaccessible."
DOM Fragment
If you use a tree to analyze garbage collection, you will find that we need to do very little, because when a function is finished, its associated objects will be cleared. Even with closures, these closures are also flagged when functions that refer to the closure are executed.
So where does a memory leak occur? Look at this example.
var btn = document.getElementById (' btn ');
Btn.onclick = function () {var fragment = document.createelement (' div ');
}
It means that every time a button is clicked, a <div> is created, it does not refer to any object, but the empty <div> is not recycled after the callback is finished.
DOM Events
var content = document.getElementById (' content ');
content.innerhtml = ' <button id= ' button ' >click</button> '; var button = document.getElementById (' button ');
Button.addeventlistener (' click ', Function () {});
content.innerhtml = ';
After this code, although <button> is removed from the DOM, it cannot be reclaimed by GC because its listener is still there.
To avoid this situation is to remove the callback function by RemoveEventListener.
Timer
If you use SetInterval, the context of the variable it refers to is preserved.
function foo () {var name = ' Tom ',
title = ' Hero ';
Window.setinterval (function () {
alert (name);
}, 1000);
Foo ();
On the other hand, you don't have to call cleartimeout to settimeout just to avoid memory leaks. It does not cause memory leaks, except for other reasons, such as recursive invocation of the current timer in settimeout, which is equivalent to analog setinterval, which can be treated like setinterval.
Summary
In peacetime some of the development process, I found that although the GC event in the Chrome, and memory dropped very low, if the profile tool Take Heap Snapshot, you will not feel a memory leak occurred. But on the mobile phone (webview) does exist more and more card-using phenomenon, which may be based on different circumstances to analyze, but the key two points mentioned in this article is: dereference, and the release of the listening event.
If you can do these two points in your own code, it may be that the cotton is caused by other problems, not memory leaks