preface
The reason is because I want to understand the memory leakage mechanism of closures, and then remembered “JS Advanced Programming” has about the garbage collection mechanism analysis, before I did not understand, after a year to read back to understand, write a blog to share with you. If you like, you can click Bozam/Follow and support it.
Personal blog: obkoro1.com
Memory life cycle:
- Allocate the memory you need:
Because strings, objects, etc., do not have a fixed size, js program in the creation of strings, objects, the program will allocate memory to store that entity.
-
Do something with the allocated memory.
-
Release it when it is not needed:
When strings and objects are not needed, they need to be released. Otherwise, all available memory in the system will be consumed and the system will crash. This is the significance of the garbage collection mechanism.
A memory leak is a waste of memory that is no longer used because a program fails to release memory due to an oversight or error.
Garbage collection mechanism:
In languages like C and C++, the need to manage memory manually is a source of many unnecessary problems. Fortunately, the allocation of memory and the collection of memory are completely managed automatically when writing JS, so we don’t have to worry about this kind of thing.
How the garbage collection mechanism works:
At regular intervals, the garbage collector periodically finds variables that are no longer in use and then frees the memory they occupy.
What is a variable that is no longer in use?
Variables that are no longer used, i.e. end-of-life variables, are local variables. Local variables exist only during the execution of a function. When the function is finished and there are no other references (closures), the variable is marked for recycling.
The lifetime of global variables does not end until the browser unloads the page, meaning that global variables are not garbage collected.
Flag clearance: The garbage collection policy currently in use
Working principle:
When a variable enters the environment (such as declaring a variable in a function), it is marked as “into the environment” and as “out of the environment” when it leaves the environment. Those marked “out of the environment” reclaim memory.
Workflow:
- The garbage collector will mark all variables stored in memory at runtime.
- Untag variables in the environment and variables referenced by variables in the environment.
- Variables that still have tags are considered to be ready for deletion.
- Finally, the garbage collector performs the final step of memory cleaning, destroying the tagged values and reclaiming the memory they occupy.
As of 2008,IE, Chorme, Fireofx, Safari, and Opera all use a marked sweep garbage collection strategy, but at different intervals.
Reference counting omitted: Deprecated garbage collection policy
Circular references: The technique of keeping track of how each value is referenced
In older browsers (IE again), IE9 BOM and DOM objects are implemented as COM objects using C++.
COM’s garbage collection mechanism uses a reference counting strategy, which never frees up memory when a circular reference occurs.
var element = document.getElementById('something'); var myObject = new Object(); myObject.element = element; // The element attribute points to the dom element. SomeThing = myObject; // someThing returns a circular reference to myObject (two objects always contain each other always exist count).Copy the code
The solution is to manually disconnect links when we’re not using them:
myObject.element = null;
element.someThing = null;
Copy the code
Elimination:
IE9 transforms BOM and DOM objects into true JS objects, eliminating the use of this garbage collection strategy and eliminating the following main causes of memory leaks common to IE9.
IE7 has one of the following notorious performance issues, you know:
- Any threshold of 256 variables, 4096 object (or array) literals, or 64KB strings triggers the garbage collector to run.
- If the lifetime of a JS script holds that many variables, the garbage collector will always run frequently, causing serious performance problems.
Internet Explorer 7 has fixed this problem.
What can cause a memory leak?
Despite the garbage collection mechanism, there are still situations when we write code that can cause memory leaks. Knowing these situations and writing programs to avoid them will make our programs more robust.
Unexpected global variables:
As mentioned above, global variables are not garbage collected, and we sometimes have the following situations in coding:
Function foo() {this.bar2 = 'default bind this to global' // global variable => window.bar2 bar = 'global variable '; // No declared variable is actually a global variable =>window.bar} foo();Copy the code
When we use the default binding, this points to the global, and this.something also creates a global variable, which many people may not have noticed.
Solution: Use strict mode or be careful in functions
function foo() { "use strict"; This. bar2 = "In strict mode this refers to undefined"; Bar = "error "; } foo();Copy the code
We can also manually free global variables:
window.bar = undefined
delete window.bar2
Copy the code
Forgotten timers and callback functions
When setInterval or setTimeout is not required, the timer is not cleared, and the callback function and internal dependent variables of the timer cannot be reclaimed, causing memory leakage.
var someResource = getData(); setInterval(function() { var node = document.getElementById('Node'); if(node) { node.innerHTML = JSON.stringify(someResource)); } // node, someResource;}, 1000);Copy the code
Solution: Manually clear the timer when the timer is finished.
Closure:
Closures can hold local variables in a function, preventing them from being released and causing memory leaks.
function bindEvent() { var obj = document.createElement("XXX"); Var unused = function () {console.log(obj,' inside a closure reference obj will not be released '); }; // obj = null; }Copy the code
Obj = null
Circular reference problem
IE9 is the following circular reference problem, mentioned above.
No DOM element references are cleaned:
var refA = document.getElementById('refA'); document.body.removeChild(refA); // dom deletes console.log(refA, "refA"); // But there are references that can console out the entire div that are not reclaimedCopy the code
If you don’t believe me, look at this DOM.
RefA = null;
Console keeps a lot of data in memory.
Too much console, such as timer console, can cause the browser to freeze.
Solution: Use console wisely, and use console as little as possible for online projects, except of course if you want to send a job.
How to avoid memory leaks:
Remember one rule: if you don’t use something, return it as soon as possible. After all, you ‘borrowed’ it.
- Reduce unnecessary global variables and use strict patterns to avoid accidentally creating global variables.
- Dereference (variables in closures, DOM references, timer cleanup) when you’re done with the data.
- Organize your logic to avoid endless loops that cause your browser to freeze and crash.
About memory leaks:
- Even a 1byte memory leak is called a memory leak, and it doesn’t have to crash or stall the browser to be a memory leak.
- It is usually the heap that leaks memory, not the stack.
Values of primitive types are in memory and are held in stack memory, and values of reference types are objects and are held in heap memory. That’s why you get memory leaks, objects, arrays, things like that.
- Using Chorme to monitor memory leaks, check out this article
conclusion
Knowing the causes of memory leaks and how they occur, we can avoid very serious memory leaks as long as we pay more attention to them during coding.
PS: I am leaving my job now, and I would like to introduce some pits. Base: Songhong Road, Line 2, Shanghai.
I hope the friends can click like/follow, your support is the biggest encouragement to me.
Personal blog and nuggets personal homepage, if need to reprint, please put the original link and signature. Code word is not easy, thank you for your support!
If you like this article, please follow my subscription number, long technical road, looking forward to learning and growing together in the future.
The above 2018.7.7
References:
JS elevation 4.3 Garbage collection
Class 4 JavaScript memory Leaks and how to avoid them
JavaScript memory leak and solution details
Class 4 JavaScript memory Leaks and how to avoid them