Browser memory leaks

Source: Internet
Author: User

1 What is a memory leak?

A memory leak is a memory resource that is not released && loses a pointer to the memory area, and the memory resource cannot be reused, resulting in a memory overflow.

What are the objects that can be manipulated in 2 JS?

There are three types of objects we can manipulate in script: JS engineobject, DOM element, and BOM element.

Jsengine Object:

var obj = Object (); var array = [];

DomElement:

var el = document.createelement (' div ');

var div = document.getElementById (' name ');

Wait a minute

Bomelement:

Window

window.location;

Wait a minute

of which only JS Engine Object and the DOM Element Yes, we can . CRUD , so there is a possibility of a memory leak.

3 JS Engine Memory recovery mechanism for Object & DOM Element

Jsengine Object recovery mechanism:

The Jscriptgarbage Collector of IE uses the mark-and-sweep algorithm, which iterates through all JS Engine object and marks unreferenced objects when garbage collection is performed, and then frees the marked memory space. Due to the mark-and-sweep algorithm, it is also very good to release the memory space of the reference island. The CollectGarbage (), which is unique to IE, is used to reclaim the JS Engine Object without reference or reference islands.

DomElement's memory recovery mechanism:

The DOM element is recycled when it is no longer referenced.

42 Ways to Leak

? Current page leaks: memory resources that refresh the page or jump to another page to release it.

? Cross-page leaks: memory resources that refresh pages or jump to other pages and cannot be freed.

4.5 Four types of leak modes

Justin Rogers summarizes 4 types of anti-patterns that can cause leaks:

? Circular References (causes a cross-page memory leak):

Circular references are the root cause of memory leaks , the bottom of other leakage patterns, or the circular references that occur. In general, the scripting engine handles circular references through their garbage collectors, but some unknown factors prevent them from triggering them to work properly. The unknown factor in IE is the state of some DOM elements accessed by some scripts.

This pattern causes a leak because of a COM reference count. The script Engine object (Translator Note: OBJ1) will hold a reference to the DOM element, waiting for all external references to be deleted before the DOM element pointer is cleaned and freed. In our case, we have two references in the scripting Engine: the Scripting engine scope and the custom properties of the DOM element. When terminated, the script engine releases the first reference, and the DOM element reference is never freed because it waits for the script engine object (Translator Note: obj1) to release it! You might think that it's easy to detect and fix this problem, but in practical applications this basic situation is just the tip of the iceberg. You might get a circular reference at the end of a 30-object chain, which is difficult to detect.


A global scripting engine variable and a DOM element construct an example of a memory leak:


Or:


Note:

To break the leak pattern, you can explicitly specify a null value. By specifying a null value before the document is unloaded, you are telling the scripting engine that there is no longer any association between the elements and the objects in the engine. Now it can clean up the reference and release the DOM element correctly. In this case, you, as a web developer, know more about the relationship between your objects than the scripting engine.

Examples of memory not leaking:


? Closures (closure leaks, resulting in cross-page memory leaks):

Closures have the lexical scope feature, which prolongs the life cycle of the method parameters and local variables, but at the same time, it is easy to introduce circular references inadvertently. As shown in the following:


In a normal circular reference, two fixed objects hold each other's references, but closures are different. Unlike directly creating references, they are created by importing information from the scope of the parent function. In general, when a function is called, the local variables of a function and the parameters used are only present in the life cycle of the function itself. When using closures, these variables and arguments continue to be externally referenced, as long as closures are still active, and since closures can survive beyond the lifetime of their parent functions, any variables and arguments in that function are also possible. In the example, Parameter 1 is normally freed after the function call ends. Because we have added a closure, the second reference is created, and the second reference is not freed until the closure itself is freed. If you happen to bind the closure to an event, you must remove it from the event. If you happen to have this closure set to a custom property, you must set this custom property to null.

Each call creates a closure, so calling this function two times will create two separate closures, each holding the arguments that were passed in. Due to this obvious feature, closures can easily cause leaks. Examples of memory leaks and non-leaks:

? cross-page Leaks (current page memory leak):

Since the node establishes a connection, it will look for scope, if not create a temporaryscope, if any, discard the original temporary scope with the existing scope, as shown in:


Examples of memory leaks and non-leaks:


Note:

whenChilddivwith theParentdivwhen establishing a connection, makeChilddivto obtainParentdivthe information,IEis createdTemporary Scope. And when theParentdivAdd toDOM TreeMedium, theChilddivand theParentdivare inheritedDocumentof theScope, whileTemporary Scopebut will not beGCrelease, and wait until the browser refreshes the page to clean up.


Note:

Always use Document Scope , does not create Temporary Scope .

? pseduo-leaks[Show Tease mode (false leak)]:

Many times, the actual performance and expected performance of some APIs can cause you to misjudge a memory leak. False leaks are almost always seen in dynamic script operations on the same page, and are rarely observable after navigating from one page to an empty page. This is how you can eliminate the cross-page leak problem and begin to see if memory usage is as expected. We will use the script text rewrite as an example of the show-tease pattern.

As with the DOM insertion order problem, this issue also relies on the creation of temporary objects to leak memory. By rewriting the script text in a SCRIPT element over and over again, you slowly begin to leak a large number of script engine objects that are inserted into the original content. In particular, objects associated with debugging scripts are discarded, just like fully formed script elements. Successive creation of multiple JS Engine Object, and the GC failed to release memory in time, in fact, is not a memory leak. For example:


If you run the above code and use Task Manager tricks again, you will not notice a script leak when navigating the leaked pages and blank pages. This kind of script leak is completely on one page, and you get your memory back when you navigate out. The reason why this example is defective is due to expected behavior. You expect the original script not to persist after rewriting some scripts. But it is actually preserved because it may already be used to bind events, and there may be external reference counts. As you can see, this is a show-and-tease pattern. On the surface, memory usage looks pretty bad, but there's a perfectly good reason.

Recommendations for prevention of leaks:

Each Web Developer creates a list of personal code cases that, when they see them in code, know that there is a leak and try to circumvent the leaks. This is convenient and is the reason why the Web is relatively non-leaking today. By considering leaks in a pattern-based approach, instead of code cases, you can start developing better strategies to deal with them. The method is to take them into consideration during the design phase and make sure you have a plan to deal with any potential leaks. Use defensive coding techniques, and assume that you must clean up all of your own memory. While this is an exaggeration of this issue, you seldom have to clean up your own memory, and it becomes obvious that there are potential leaks of variables and custom properties.

Browser memory leaks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.