Deep understanding of Memory leakage in JavaScript programs _ javascript skills

Source: Internet
Author: User
This article mainly helps you understand the memory leakage issue in JavaScript programs. If you are interested, you can refer to the garbage collection to free us, it allows us to focus on application logic rather than memory management. However, garbage collection is not magical. Understand how it works, and how to make it retain the memory that should have been released a long time ago, you can achieve faster and more reliable applications. In this article, we will learn a system method to locate memory leaks in JavaScript applications, several common leak modes, and appropriate methods to solve these leaks.

I. Introduction

When processing scripting languages like JavaScript, it is easy to forget that each object, class, String, number, and method needs to be allocated and reserved. The language and runtime Garbage Collector hides the details of memory allocation and release.

Many features can be implemented without considering memory management, but ignore the major problems that may arise in the program. Objects that are improperly cleaned may take longer than expected. These objects continue to respond to events and consume resources. They can force browsers to allocate memory pages from a virtual disk drive, significantly impacting computer speed (in extreme cases, leading to browser crashes ).

Memory leakage means that any object still exists after you no longer own it or need it. In recent years, many browsers have improved the ability to reclaim memory from JavaScript during page loading. However, not all browsers have the same running mode. Both Firefox and earlier versions of Internet Explorer have experienced memory leaks, and the memory leaks continue until the browser is closed.

In the past, many classic modes that caused Memory leakage do not cause memory leakage in modern browsers. However, there is a different trend that affects memory leakage. Many people are designing Web applications that run on a single page without a hard page refresh. In such a single page, from one state of the application to another, it is easy to retain memory that is no longer needed or irrelevant.

This article describes the basic lifecycle of an object, how to determine whether an object is released, and how to assess potential leakage behavior. In addition, learn how to use Heap Profiler in Google Chrome to diagnose memory problems. Some examples show how to solve the memory leakage caused by closures, console logs, and loops.

Ii. Object Lifecycle

To learn how to prevent memory leakage, you need to understand the basic lifecycle of the object. When an object is created, JavaScript automatically allocates the appropriate memory for the object. From this moment on, the garbage collector will constantly evaluate the object to see if it is still valid.

The garbage collector periodically scans objects and calculates the number of other objects that reference each object. If the number of references to an object is 0 (no other object has referenced this object), or the unique reference to this object is cyclic, the memory of this object can be recycled. Figure 1 shows an example of memory Recycle by the garbage collector.

Figure 1. Reclaim memory through garbage collection

The actual application of the system is helpful, but the tools that provide this function are limited. One way to learn how much memory your JavaScript Application occupies is to use system tools to view the browser's memory allocation. There are multiple tools to provide you with the current use, and describe a process's memory usage trend chart over time.

For example, if XCode is installed on Mac OSX, you can start the Instruments application and append its activity monitor tool to your browser for real-time analysis. In Windows®You can use the task manager. If you find that the memory usage increases steadily over time during your application usage, you will know that there is a memory leak.

Observe that the memory usage of the browser can only roughly display the actual memory usage of JavaScript applications. Browser data does not tell you which objects have been leaked, nor does it guarantee that the data exactly matches the real memory usage of your application. In addition, due to implementation problems in some browsers, DOM elements (or alternative application-level objects) may not be released when the corresponding elements are destroyed on the page. This is especially true for video tagging, which requires the browser to implement a more refined infrastructure.

People have tried to add a trace of memory allocation in the client's JavaScript library for many times. Unfortunately, all attempts are not particularly reliable. For example, the popular stats. js package cannot be supported due to inaccuracy. Generally, an attempt to maintain the information from the client or determine whether there is a problem because it will introduce overhead in the application and cannot be reliably terminated.

The ideal solution is that browser vendors provide a set of tools in the browser to help you monitor memory usage, identify leaked objects, and determine why a special object is still marked as retained.

Currently, only Google Chrome (with Heap Profile) implements a memory management tool as its developer tool. I used Heap Profiler in this article to test and demonstrate how to handle memory during JavaScript runtime.

3. Analyze heap snapshots

Before creating a memory leak, check a simple interaction that properly collects the memory. First, create a simple HTML page containing two buttons, as shown in Listing 1.

Listing 1. index.html

 

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.