SoFunction
Updated on 2025-04-12

How to improve the performance of javascript code

I originally had to summarize this code performance article after writing maintainability code articles. After a few days of delay, I decided to update an article every day because I owe too many things to summarize before, and I really forgot what I learned to not summarize. I recorded that I left a deeper impression on your brain, especially these maintainability codes, performance, etc. When a habit is formed in your mind, you will be awesome! Here I would also like to give beginners a suggestion: summarize more things you have learned, because this is actually learning new knowledge! OK, go to our topic: How to improve the performance of JS code.

1. Optimize DOM interaction

DOM is closely related to our page. The browser renders the page, that is, renders the parsed DOM elements. DOM operations and interactions take a lot of time because they often require re-rendering the entire page or part. Further, some seemingly subtle operations may also take a lot of time to execute, because the DOM needs to process a lot of information, so we should optimize DOM-related operations as much as possible to speed up the browser's rendering of the page! Why some DOM operations affect page performance? You can check out some articles I wrote about the principles of the browser:

OK, we mainly have several ways to optimize DOM operations:

1.1 Minimize on-site updates

What is a live update of DOM: An immediate update is required to display a portion of the page that has been displayed in the DOM part. However, every change, whether it is inserting a single character or an entire piece of fragment, has a certain performance penalty, because the browser needs to recalculate countless sizes for updates (please read about it for related knowledge:). Therefore, the more updates are performed on site, the longer the code execution time will take, and vice versa, the faster the code execution, as follows:

var list = ('mylist'),
      item,
      i;
for(i = 0; i < 10; i++){
  item = ('li');
  (item);
  (('item' + i));
}

This code adds 10 items to the list mylist. If no one is added, you need to perform 2 on-site updates: adding elements and adding text nodes. Therefore, this operation requires 20 on-site updates, and each update will lose performance. It can be seen that such code runs relatively slowly.

The solution is to use document fragmentation to indirectly change the DOM element:

var list = ('mylist'),
      fragment = (),
      item,
      i;
for(i = 0; i < 10; i++){
  item = ('li');
  fragment .appendChild(item);
  (('item' + i));
}
(fragment);

Code like this only requires a live update once. Remember, when passing in document fragments to appendChild(), only child nodes in document fragments will be added to the target element, and the fragment itself will not be added.

Now, you should understand how sorry you are to the browser by directly adding, deleting, checking and modifying DOM nodes using loops `(∩_∩)′.

1.2 Using innerHTML

In addition to the method of creating DOM elements combined with creatElement() and appendChild() used in the above code, it is also created by assigning values ​​to innerHTML. For small DOM changes, the efficiency of the two methods is actually similar, but for a large number of DOM node changes, the latter is much faster than the former! Why pinch?

Because when we assign values ​​to innerHTML, the background will create an HTML parser, and then use the internal DOM call to create a DOM structure, rather than a Javascript-based DOM call. Since the internal methods are compiled rather than interpreted and executed, the execution speed is much faster!

Rewrite the above example using innerHTML:

  var list = ('mylist'),
       html = '', //Declare an empty string        i;
  for(i = 0; i &lt; 10; i++){
    html += '&lt;li&gt;item' + i + '&lt;/li&gt;';
  }
   = html; // Remember here that the four letters of HTML after innerHTML must be capitalized!

This method also only undergoes a live update once, and the performance is better than the previous method! Although there is a bit of performance loss on the linking of strings.

1.3 Using Event Agent/Event Delegation

Event handlers provide interactive capabilities for web applications, so many developers will add a large number of handlers to the page indiscriminately. One problem is that the number of event handlers on a page will directly affect the overall operation performance of the page. Why pinch?

First, the event handler corresponds to at least one function. Each function in JS is an object and will occupy memory. The more objects there are in memory, the worse the performance.

Secondly, we must specify all event handlers in advance, which leads to an increase in the number of DOM visits, which delays the interaction readiness time of the entire page, and the page responds to user operations relatively slowly.

Therefore, reducing event handlers can also make our page more smooth! It is inevitable to use the event delegation!

The principle of event delegation is actually event bubbles. Only one event handler can manage all events of a certain type of operation. For example: the click event will bubble up to the document level, which means we don’t have to add events to each element. We just need to add an event handler to the higher level elements, and then use the attributes or methods of the event object (event) to judge the currently clicked element, and then make a corresponding response. I won’t go into this. Beginners can check the bubble knowledge of events by themselves.

2. Scope is important

When it comes to scope, it is easy to think of scope chains. We know that to search for a variable, the execution environment in which we are located must search for this variable upward along this scope. There are many variables on the scope chain, so we have to traverse. It takes time to traverse, and the more time you need to search upwards. If we can reduce this time, can we improve the execution efficiency of our code?

So smart, OK, I'll see what ways to reduce this time:

2.1 Avoid global searches

This is a key point of performance optimization. As mentioned above, the more time you look up, the more you look up, that is, it is more than local! Look at the code:

function updateUI(){
  var imgs = ('img');
  for(var i = 0 ,lng = ;i < lng;i ++){
    imgss[i].title =  + 'image' + i;
  }
  var msg = ('msg');
   = 'update complete.';
}

This code is normal! I've done this often before. But we can find carefully that there are three references to the global variable document in this code. If our page has many pictures, the document in the for loop will be executed hundreds of times, and each time it needs to be searched in the scope chain. Where has the time gone? I haven't...stopped! .

We can save the reference to the document by creating a local variable in the function, so that we don’t have to go to the global variable to find the document anywhere in the function. This improves the performance of the code, see the code:

function updateUI(){
  var doc = document; // Save document in local variable doc  var imgs = ('img');
  for(var i = 0 ,lng = ;i &lt; lng;i ++){
    imgss[i].title =  + 'image' + i;
  }
  var msg = ('msg');
   = 'update complete.';
}

So, in development, if we often use global variables in functions, save them in local variables!

2.2 Avoid using with statements

Using the with statement to extend the scope, it also takes time to find variables. We generally won't use this, so we won't expand it. The solution is the same as in the above example, save the global variable in the local variable!

3. Optimize the loop

Loops are common in programming and can be seen everywhere in js. The loop body will repeatedly execute the same piece of code, and the execution time is always accumulated, so being able to optimize the code of the loop body can greatly reduce the execution time! How to optimize? Four ways.

3.1 Impairment Iteration

This is usually the case when we write iterators (loop conditions) (var i = 0;i < 10;i ++), starting from 0 and increasing to a specific value. However, in many cases, it is more efficient if the impairment iterator is used in the loop. I tested it and if the loop body is not complicated, the two are almost the same!

//Value-added iteration -- Low efficiencyfor(var i = 0;i &lt; ;i++){
  doSomething(items[i]); 
}
//Impairment iteration -- Higher efficiencyfor(var i =  - 1;i &gt;= 0;i--){
  doSomething(items[i]); 
}

3.2 Simplify the termination conditions

Since each loop calculates the termination condition, it must be ensured that it is executed as much as possible. This is mainly to avoid searching other DOM elements and their attributes.

 //Look at the termination condition, each loop needs to query items and their length attributesfor(var i = 0;i &lt; ;i++){
  doSomething(items[i]); 
}

//Save the value in the local variable lng.for(var i = 0,lng = ;i &lt; lng;i++){
  doSomething(items[i]); 
}

3.3 Simplify the circulation body

The reasons are as follows: A large number of intensive operations are avoided in the circulation body.

This is actually the same as mentioned above: 1.1 Minimize on-site updates. It's the same optimization method. You can go back and take a look.

4. Basic algorithm optimization

In computers, the complexity of the algorithm is expressed in O. Here are several common algorithm types in JavaScript:

O(1): A constant, no matter how many values ​​there are, the execution time is constant, such as simple values ​​and values ​​stored in variables.
O(log n): logarithm, the total execution time is related to the quantity, but it does not necessarily need to obtain each value, such as: dichotomous search
O(n): linear, the total execution time and quantity are directly related, such as: traversal
O(n*n): square, the total execution time is related to the number, and each value is obtained at least N times, such as: insert sort
OK, with the above knowledge, we can perform some algorithmic optimizations on JavaScript. Look at the code:

var value = 5;
var sum = value + 10;
alert(sum);

This code searches for constant values ​​4 times: number 5, variable value, number 10, variable sum, the algorithm complexity of this code is O(1). Another example:

var value = [10,5];
var sum = value[0] + value[1];
alert(sum);

Accessing array elements in javascript is also an O(1) operation, which is the same as simple variable searching. Look again:

var value = {one:10,two:10};
var sum =  + ;
alert(sum);

What to express is that accessing properties on objects is less efficient than accessing arrays and variables. Because this is an O(n) operation. You need to look up the property in the object's prototype chain, which takes a lot of time.

Okay, after reading this, do you feel bright in front of you? In fact, what we mentioned earlier is to save the frequently used global attributes in a local variable. This is based on this principle. Accessing global attributes is an O(n) operation, while accessing variables is an O(1) operation. Tell me loudly which excavator is the best!

5. Minimize the number of statements

The optimization mentioned above is almost related to streamlined optimization statements. Yes, I think the quality and quantity of code are the criteria for judging performance. I have talked about some optimizations related to code quality, and here I will talk about optimization of code quantity.

5.1 Simplified variable declaration

// 5 variables were declared using 5 statementsvar count = 5;
var color = 'red';
var values = [1,2,3];
var now = new Date();

//A statement was used to declare 5 variables, please note that each variable is separated by a comma.var count = 5,
  color = 'red',
  values = [1,2,3],
  now = new Date();

5.2 Using arrays and object literals

// Create two objects ----bad way//one four statementsvar values = new Array();
values[0] = 123;
values[1] = 456;
values[2] = 789;
//two four sentencesvar person = new Object();
 = 'jozo';
 = 21;
 = function(){
  alert();
};
// Create two objects ----Recommended method//one 1 statementvar values = [123,456,789]
//two 1 sentencevar person = {
  name : 'jozo',
  age : 21,
  sayName : function(){
  alert();
};

6.Others

If you are tired of writing, please correct me if there are any incorrect points. There are some other optimizations. The article will continue next time!