In fact, no matter what you’re developing, you’re going to have a memory leak. But ultimately, most of the problems are in the code. As ambitious developers, we should not only pursue functionality, but also the performance of the code. I’m going to take a moment today to talk about so-called memory leaks.

### what is a memory leak a bit basic program know, the program is running need to allocate memory space. In the case of a continuously used web page, if some unused memory is not released in time, this is called a memory leak. But as we all know, our webpage terminal capacity is limited, constantly blowing to a balloon inside, the balloon always has a moment of blowing. The browser is just crashing.

Reference counting

For the method of memory leak identification, I mainly learn from ruan Dashen’s blog. There are two types: browser and command line

3.1 browser

  • First open Chrome, then press F12 (Windows)/Option + Command + I to open the debugging tool and select Memory.
  • According to the following view we see that there is a total ofHeap snapshot.Allocation instrumentation on timeline.Allocation samplingThree types of heap snapshot
  • Before recording, click Garbage Collection first, then click Record, but if it is the DYNAMIC time line of JS heap memory allocation, click garbage Collection again before ending recording.

3.1.1

  • Summary Overview view: Grouped by constructor. Used to capture objects and the memory they use. This is especially useful for locating DOM memory leaks.
  • Comparison Comparison view: compares two snapshots. It is used to compare heap snapshots after different operations to see the memory release and reference count to analyze whether the memory leaks and their causes.
  • Containment content view: View the heap contents. It is better to look at the structure of the object, which helps to analyze object references. Good for parsing closures as well as deep parsing objects. + Statistics Statistics view: Displays heap Statistics.
3.1.1.1 Summary Overview View

  • Objects under a node are created from the Constructor.
  • Distance: The Distance to the root node.
  • Objects Count: Number and percentage of Objects.
  • Shallow size: Total direct memory of the object (Shallow size). Direct memory refers to the amount of memory occupied by the object itself.
  • Retained size: Specifies the maximum Retained memory of the object. Retained memory refers to the memory that can be released after the object is deleted.

Click to expand the constructor to see all constructor-related object instances, with the number after @ being the unique identifier of the object instance.

Common top-level constructors:

  • (Global Property) : An intermediate object between a global object and a normal object. For example, if a Person object is defined on a Window, the relationship between them is [global] => (global Property) => Person. Intermediate objects are used for performance reasons.
  • Closure: Object that uses a function closure.
  • (array, a string, number, the regexp) : a series of object types, its attribute points to an array/string/number/regexp.
  • HTMLDivElement/HTMLAnchorElement/DocumentFragment: element reference or code of the specified document reference object.
3.1.2 Comparasion Comparison view

To verify whether a specific operation will cause a memory leak, perform the following steps to compare a snapshot: 1. Take the first heap snapshot without performing any operations. 2

3.1.2 JS heap allocation timeline

With Allocation instrumentation on timeline, the heap Allocation can be continuously recorded, showing when the object is created and when there is a memory leak.

Here is the Vue project switching between two recorded heap allocations over and over again. We can focus on one heap allocation to see the specific object information. You can scroll the mouse wheel in the bar chart to see the heap allocation for a certain period of time. For example, three VueComponent were not collected. Click to expand for details. It was found that the information for all three components was the same, that the component was not released. First verify that the component is destroyed. If so, check whether the event is unbound and whether the timer is cancelled. In particular, the events bound to the event bus must be unbound.

3.2 command line

The command line can use the Process. memoryUsage method provided by Node. Process. memoryUsage returns an object containing memoryUsage information for Node processes. This object contains four fields, in bytes, with the following meanings.

  • Resident set size (RSS) : All memory usage, including instruction area and stack.
  • HeapTotal: The amount of memory occupied by the heap, both used and unused.
  • HeapUsed: part of the heapUsed.
  • External: memory occupied by C++ objects inside the V8 engine.

The heapUsed field is used to determine memory leaks.

Because in a single page of VUE, the page is not refreshed when the page jumps, which causes the accumulation of memory leakage, resulting in page lag or page crash. Here are some of the memory leaks I encountered during development. # # # # 4.1, closures

function closure(){
    var element = document.getElementById('mydiv'); // Element stays in memory after it is usedtest = element.innerHTML;
    element.onclick = function () {
        alert(test); // Here we use element to leak memory}; } closure();function closure(){
    var element = document.getElementById('mydiv');
    var test = element.innerHTML;
    element.onclick = function () {
         alert('test'); }; element = null; }}Copy the code

####4.2. Unexpected global variables

function foo(arg) {
    bar = "aaaaa"; } is actually equivalent tofunction foo(arg) {
    window.bar = "aaaaa";
}
Copy the code

This is a situation that many people will see, and I recommend using ES6 let or strict mode. ####4.3 timers

var data=getData();  
setInterval(function(){  
    var node=document.getElementById("name");  
    if(node){  
        node.innerHTML=JSON.stringify(data)  
    }  
},1000)  
Copy the code

####4.4. Global events are used in the life cycle and no release is done

onCreate(){
  bus.%on(' ')},beforeDestroy() {
  bus.$off('* * * *');
}
Copy the code

####4.5, cross-references between DOM objects and JS objects, not null

var obj = {}; 
document.getElementById('idname').property = testObject; // Obj will persist until dom is reclaimed, which may cause a memory leakCopy the code

Solutions:

window.onunload=function(){
    document.getElementById('idname').property = null; // Free memory};Copy the code

####4.6. What if you want to keep the state and elements in memory when the keep-alive component removes elements? In this case, you can use the built-in keep-alive component. When you wrap a component with keep-alive, its state is preserved and therefore remains in memory.

<button @click="show = false">Hide</button> <keep-alive> <! -- '<my-component>' will intentionally remain in memory even if deleted --> <my-component v-if="show"></my-component>
</keep-alive>
Copy the code

This technique can be used to improve the user experience. For example, imagine a user enters a comment in a text box and then decides to navigate away. If the user navigates back later, those comments should still be there.

Once you use keep-alive, you can access the other two lifecycle hooks: Activated and deactivated. If you want to clean up or change data when a keep-alive component is removed, use the Deactivated hook.

deactivated: function() {// Remove any data you don't want to keep}Copy the code

####4.7 memory leak solution caused by Echarts

   chart.dispose(myChart)
   myChart = chart.init(document.getElementById(dom));
  myChart.setOption(option);
Copy the code

Said in the last

In fact, the so-called memory leakage, is nothing more than used things are not timely recycling leads to part of the memory occupied for a long time, a good programmer will not let the memory to maintain a high occupancy state for a long time. While the front end is all about implementation and page effects, there’s a bit of a story about page performance. As a programmer with pursuit, I still hope I can pay more attention to these aspects and improve my professional knowledge accumulation when knocking code.