Several JavaScript performance optimization tips

Several JavaScript performance optimization tips

This article is translated from John Au-Yeung's JavaScript Best Practices Performance , please refer to the original text to read

Like any other programming language, JavaScript also has its own list of best practices to make programs easier to read and maintain. JavaScript has many tricky parts, so some practices that reduce the quality of the code should be avoided. By following best practices, we can create elegant and manageable code that anyone can use easily.

In this article, we will explore ways to improve application performance, including caching data in variables, using the fastest method to loop through variables, reducing DOM access and elements on the page, and delaying script loading.

Reduce access to variables and attributes

We should reduce the number of visits to variables and object properties in the application.

This is because every time this operation is performed, the CPU has to access the items in memory again and again to calculate the result.

Therefore, we should do as little as possible.

For example, for a loop, it should not look like this:

for(let i = 0; i < arr.length; i++) {
}
 

Instead, it should be written as:

let length = arr.length;
for (let i = 0; i < length; i++) {

}
 

In this way, arr.length is only referenced once in our loop, instead of accessing it in each iteration.

The fastest way to loop through variables

In JavaScript, there are multiple ways to traverse an iterable object. One is the old for loop, and the other methods include for...of loops and the forEach method of arrays. The map and filter operations also traverse the array. There is also a while loop.

Of all the ways to run a loop, the for loop is the fastest way, regardless of whether the length is cached as above, the for loop is the same. However, caching the length sometimes makes the loop perform better.

Some browser engines optimize the for loop without caching the length attribute.

The while loop with decreasing index is about 1.5 times slower than the for loop.

Using forEach loops is 10 times slower than for loops, so it is best to avoid using it, especially for large arrays.

We can see the result here.

Reduce DOM access

Accessing the DOM is an expensive operation because the browser must get the element from the web page, then create an object from it and return it.

In order to reduce DOM access, if we need to manipulate the DOM Node object multiple times, we should assign it to a variable.

For example, if we have the following HTML and want to set some text for it in a few seconds:

<p id='foo'>
</p>
 

We can write the following code to do this:

const setText = (element, textContent) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      element.textContent = textContent;
      resolve();
    }, 3000)
  })
}
(async () => {
  const foo = document.querySelector('#foo');
  await setText(foo, 'foo');
  await setText(foo, 'bar');
  await setText(foo, 'baz');
})();
 

In the above code, we have a function to get the HTML element we want to manipulate and the text content to be set.

The setText function returns a promise and will set the text to the given element after 3 seconds.

Then we have an async function to set the text 3 times. The core part is that we pass the reference of the element to it every time we call it. In this way, we don't have to get elements from the web page every time, which is an expensive operation.

Reduce DOM size

The DOM tree is very slow to render. Therefore, we must reduce the size of the tree.

This individual has no choice but to make our website as simple as possible.

When the DOM is small, you can search for elements faster by using methods such as querySelector, getElementById, or getElementsByTagName because there is less search content.

In addition, because less content is loaded, page rendering performance will also improve. This is especially true for slower devices such as mobile phones and tablets.

Don't declare unnecessary variables

Every time we declare a variable, the browser must allocate storage space for the variable. Therefore, in order to reduce memory usage, we should not declare too many variables.

For example, if we have the following HTML:

<div id='foo'>
  <p>
  </p>
</div>
 

We want to set the text content of the p element, we shouldn't write like this:

const foo = document.querySelector('#foo');
const p = foo.querySelector('p');
p.textContent = 'foo';
 

Because we have 2 variables here, this means that our computer must store the values of 2 additional JavaScript variables.

We can reduce variable declarations by writing the following code:

document.querySelector('#foo p').textContent = 'foo';
 

As we have seen, we can use the querySelector method to select any content through CSS selectors. This means that we should use this method and the related querySelectorAll method to select elements, because they can use CSS selectors to select any HTML element node.

Delaying the loading of scripts Loading JavaScript files is an expensive operation. The browser must download the file, parse the content, and then convert it into machine code and run it.

The browser downloads a file while blocking any other operations.

Therefore, we should delay it as much as possible. We can do this by putting the script tag at the end. In addition, we can use the defer attribute on the script tag to perform this operation.

In addition, we can dynamically create script elements after the page is loaded and run the script as follows:

window.onload = () => {
  const element = document.createElement("script");
  element.src = "https://code.jquery.com/jquery-1.12.4.min.js";
  document.body.appendChild(element);
};
 

After the page is loaded, you can use the loading method of this script to load any content.

summary

We can do something to speed up the page. 1. we can cache the data in variables, so we don't have to access them repeatedly. Then, we can use a for loop to traverse the items faster.

In addition, we can reduce the DOM size to reduce the items that need to be loaded. We can also cache DOM objects in their code by assigning them to variables.

We should not declare unnecessary variables, and we should postpone the loading of the script as much as possible, so as not to block our browser.