JavaScript Memory leakage prevention and memory management skills, javascript Memory Management

Source: Internet
Author: User

JavaScript Memory leakage prevention and memory management skills, javascript Memory Management

This example describes how to use JavaScript to prevent memory leakage and manage memory. Share it with you for your reference. The specific method is as follows:

This article originated from Google WebPerf (London WebPerf group) in August 26, 2014.

In general, efficient JavaScript Web applications must be smooth and fast. Any application that interacts with the user needs to consider how to ensure the effective use of memory, because if the consumption is too large, the page will crash and force the user to reload. You can only hide in the corner and cry.

Automatic garbage collection cannot replace effective memory management, especially in large, long-running Web applications. In this article, we will demonstrate how to effectively manage the memory through Chrome's DevTools.

Learn how to solve performance problems, such as memory leakage, frequent garbage collection pauses, and overall memory expansion, which truly consumes your energy.

Addy Osmani shows many examples of Memory leakage in Chrome V8 in his PPT:

1) Deleting an Object attribute slows down the Object (15 times more memory consumption)

Var o = {x: 'y'}; delete o. x; // at this time, o will become a slow object o. x; // var o = {x: 'y'}; o = null; // this should be the case

2) Closure

When a variable outside the closure is introduced to the closure, the object cannot be garbage collection (GC) when the closure ends ).

var a = function() { var largeStr = new Array(1000000).join('x'); return function() {  return largeStr; }}();

3) DOM Leakage

When the original COM is removed, the sub-node reference cannot be recycled if it is not removed.

Var select = document. querySelector; var treeRef = select ('# tree'); // In the COM tree, leafRef is a subnode of treeFre. var leafRef = select (' # leaf '); var body = select ('body'); body. removeChild (treeRef); // # tree cannot be returned because treeRef is still in progress. // solution: treeRef = null; // tree cannot be recycled yet, because the leaf result leafRef is still in leafRef = null; // now # tree can be released.

4) leakage of Timers Timer

The timer is also a common cause of Memory leakage:

For (var I = 0; I <90000; I ++) {var buggyObject = {callAgain: function () {var ref = this; var val = setTimeout (function () {ref. callAgain () ;}, 90000) ;}} buggyObject. callAgain (); // although you want to recycle it, timer is still buggyObject = null ;}

5) debugging memory

Chrome's built-in memory debugging tool allows you to conveniently view memory usage and Memory leakage:

In Timeline-> Memory, click record:

I hope this article will help you learn javascript programming.


How does javascript solve an instance of Memory leakage?

First, you need to correct/understand the so-called closure. For more information, see my answer here: zhidao.baidu.com/question/586170392.html? Oldq = 1

After you have clearly understood the closure, you will find the problem by looking at the code above.
Element. onclick = function () {alert (element. id);} Here, The onclick of the element object points to your anonymous function, so we can first make it clear that before the element Object is released, your anonymous function cannot be released.
The problem is, can an element object be released at a certain time in the future? No! Because your anonymous function references the element Object again!
That is to say, the element Object references your anonymous function, and your anonymous function references the element. The results form a circular reference. This is the problem.

In this case, memory leakage occurs. However, it is not necessary to study it carefully. Although circular references are formed here, the modern garbage collector does not simply check whether the reference count of an object is 0 to determine whether it can be recycled. It depends on whether there is a path from the root object to the object. Simply put, for the modern garbage collector, such a simple ring reference will not cause memory leakage.


How to Avoid C/C ++ Memory leakage in projects

In C/C ++ software engineering implementation, memory leakage may be a headache for many programmers. memory leakage is so common and is considered difficult to solve. It indicates that memory leakage is not a theoretical problem, but a practical problem. if it is a theoretical problem, it must have been resolved theoretically, rather than a problem. in software engineering practice, efforts should be made to adopt good design policies and code habits to avoid Memory leakage; to avoid this is not to avoid difficulties, but to avoid memory leaks throughout the Code, resulting in uncontrollable risks and fatigue caused by the test phase. the following summarizes several design principles related to memory leakage: 1. try not to design the internal memory allocation and the memory is transferred to the external interface; 2. when the memory is allocated internally by the system or module and needs to be transferred to the outside (when the interface requirements cannot be modified ), in order to clear the memory allocated internally when the specific context, thread, and environment are terminated, the system needs to introduce a possibly not complex global memory manager; 3. all memory allocation/release operations in the specific context/thread/environment system are tracked through the memory manager. When the software grows, the use of multiple allocation methods will only lead to confusion and inevitably lead to memory leakage; 4. for interfaces related to specific contexts, threads, and environments, the outside cannot know the buffer size requirements in advance (for example, I/O, usually internal buffer and sufficient status and information ), or it has nothing to do with the specific context, but can know the interface (for example, the Protocol package serialization parameter contains the size) that needs to be buffered according to the input parameters. The interface must support: first pass the NULL buffer pointer, return the required buffer size. If the input buffer size is too small, the system returns a small buffer error code. If the input buffer is sufficient, the system copies the output data. 5. an interface in the system that has nothing to do with the specific context or already exists. When the outside cannot know the buffer size requirements in advance, it is encapsulated using the specific context and its allocated memory is registered in the memory manager, after use, you need to call the Memory Manager Release Interface to release it explicitly, and try to control its usage within a specific level. 6. use a memory leak tool to check the entire system.

Related Article

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.