Make writing a habit together! This is the 11th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

⭐ ⭐

答 案 : Browser

A:

You can use the Performance and Memory options of chrome Development tools to troubleshoot Memory leaks.

Write two functions, one for deliberately creating a lot of DOM elements and one for constantly pushing a lot of data in an array, and then use a timer to execute both functions over and over again.

function createNodes () {
  for(let i = 0; i < 100; i++) {
    let div = document.createElement('div')
    div.appendChild(document.createTextNode(i))
    document.body.appendChild(div)
  }
}

let arr = []
function createArray() {
  let foo = new Array(100000).fill({
    name: 'lin'
  });
  arr.push(foo)
  console.log(arr)
}

setInterval(() = > {
  createArray()
  createNodes()
}, 1000);
Copy the code

At this point, open Chrome’s Developer panel, click on the Performance panel, and take a snapshot, as shown below.

As you can see, the JS Heap and Nodes lines are increasing over time because the test code we just wrote is working.

But this snapshot alone doesn’t tell you what went wrong, given the complexity of function calls in real projects.

At this point, you can open the Mermory panel, which shows the memory footprint of each item, as shown in the figure below.

We can clearly see that the first array takes up a lot more memory than the other items, so we can focus on how the array was created.

When you look at the data, it’s exactly what we just tested the code generated.

At the end

In actual projects, if there is a lag, it is likely to be caused by a memory leak. If there is no subjective judgment of what is wrong in the code, you can use this method to troubleshoot and correct errors.

Alin level is limited, the article if there are mistakes or improper expression of the place, very welcome to point out in the comment area, thanks ~

If my article is helpful to you, your 👍 is my biggest support ^_^

You can also follow the front End Daily Question column in case you lose contact

I’m Allyn, export insight technology, goodbye!

The last:

The “Front End of the Day question (47)” talks about MEMORY management of JS, and gives some examples of memory leaks.

Next up:

Front End Daily Question (49) what are imperative and declarative frameworks?