How can you improve the performance of javascript code

  • 2020-05-24 05:11:39
  • OfStack

Originally in the maintainability code article will summarize the article code performance, after delay for several days, was also decided to update 1 article every day, because owe too much things no summary, learned things didn't go to summarize really soon forgot, record 1 a deeper impression in your brain, especially the code maintainability, performance of what, when your mind is a kind of habit, then you are cattle! Here is also a tip for beginners: summarize what you have learned, because it is also learning new knowledge! Ok, let's move on to our topic: how to improve the performance of JS code.

1. Optimize the DOM interaction

DOM is closely related to our pages. Browser rendering pages are DOM elements after rendering and parsing. DOM operations and interactions consume a lot of time, because they often need to re-render the whole page or part 1. As a further step, seemingly trivial operations can also take a lot of time to perform, because DOM has a lot of information to process, so we should optimize the operations related to DOM as much as possible to speed up the rendering of the page by the browser! Why some DOM actions affect page performance, check out my article on how browsers work:

ok, to optimize DOM operation, we mainly have a few ways:

1.1 minimize on-site updates

What is a live update of DOM: the display of part 1 of the page already displayed in the DOM section needs to be updated immediately. However, each change, whether inserted as a single character or as a whole fragment, has a definite performance penalty because the browser needs to recalculate an infinite number of dimensions to update (read :). Therefore, the more on-site updates are made, the longer the code execution time will be; on the contrary, the faster the code execution will be, as follows:


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

This code adds 10 items to the list mylist, and every item that is not added needs to be updated twice in the field: adding elements and adding text nodes. Therefore, this operation needs to complete 20 field updates for each one, and each update will lose performance. It can be seen that such code runs relatively slowly.

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


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

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

Now, you should know how sorry you are for the browser to loop directly to the DOM node. '(∩_∩)'.

1.2 use innerHTML

In addition to the combination of creatElement() and appendChild() used in the code above to create the DOM element, it is also created by assigning a value to innerHTML. For small DOM changes, the efficiency of the two methods is about the same, but for a large number of DOM node changes, the latter is much faster than the former! Why to knead?

Because when we assign innerHTML, we create an HTML parser in the background, and then use the internal DOM call to create the DOM structure, instead of the Javascript-based DOM call. Because the internal methods are compiled rather than interpreted, the code executes much faster!

Rewrite the above example with innerHTML:


  var list = document.getElementById('mylist'),
       html = '', // The statement 1 Empty strings 
        i;
  for(i = 0; i < 10; i++){
    html += '<li>item' + i + '</li>';
  }
  list.innerHTML = html; //  Remember here innerHTML At the back of the HTML4 Capitalize every letter! 

This method also only carried out one field update, and the performance is better than the previous one! Although there is a bit of a performance penalty on string linking.

1.3 use event proxies/event delegates

Event handlers provide the ability to interact with web applications, so many developers add a large number of handlers to the page indiscriminately. One problem is that the number of event handlers on a page is directly related to the overall performance of the page. Why do you pinch?

First, the event handler corresponds to at least one function. Each function in JS is an object, which takes up memory. The more objects in memory, the worse the performance.

Second, we have to specify all event handlers in advance, which results in more visits to the DOM, delays the interaction-ready time of the entire page, and makes the page relatively slow to respond to user actions.

So reducing the number of event handlers can also make our pages more beautiful! The use of event entrustment is a must!

The principle of event delegation is essentially event bubbling, with only one event handler specified to manage all events for a type 1 operation. For example, the click event will bubble up to the document level, which means that we don't need to add an event to every element, we just need to add an event handler to the element at a higher level, and then use the attributes or methods of the event object (event) to judge the currently clicked element, and then make the corresponding response. I'm not going to go through this, but beginners can look it up on their own.

2. Scope is important

Say to scope is easy to think of the scope chain (scope chain), we know that to search for a variable, the execution environment is upward along the scope search this variable, there are a lot of scope chain variable, so we'll have to traverse, traverse it need time, and the more you up for the time required, if we can reduce the time, we can code execution efficiency is not improved?

So smart, ok, let me see what I can do to reduce this time:

2.1 avoid global lookups

This is a key point of performance optimization. As mentioned above, the higher up you go, the more time you spend looking for global variables and functions. Look at the code:


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

This code is normal! I used to do that all the time. However, we can notice that there are three references to the global variable document in this code. If we have many images on our page, document in for loop will be executed hundreds of times, and each time we need to look in the scope chain. Where does the time go? Stop! .

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


function updateUI(){
  var doc = document; //  will document Save in local variables doc In the 
  var imgs = doc.getElementByTagName('img');
  for(var i = 0 ,lng = imgs.length;i < lng;i ++){
    imgss[i].title = doc.title + 'image' + i;
  }
  var msg = doc.getElementById('msg');
  msg.innerHTML = 'update complete.';
}

So, in development, if we're going to use a global variable a lot in a function, save it in a local variable!

2.2 avoid with statements

The scope is extended with the with statement, and finding variables also takes time, which we don't usually use, so we won't expand. The solution is to save the global variables in the local variables as shown in example 1 above!

3. Optimize the loop

Loops are so common in programming that they can be seen everywhere in js. Loops can execute the same piece of code over and over again, and the execution time increases. Therefore, optimizing the code in the loop can greatly reduce the execution time! How to optimize? Four ways.

3.1 impairment iteration

This is how we always write iterators (var i = 0; i < 10; i ++), starting at 0 and increasing to a certain value. In many cases, however, it is more efficient to use an impairment iterator in a loop. I tested it, and if the loop wasn't complicated, it would be about the same!


// Increment iteration  -- Low efficiency 
for(var i = 0;i < items.length;i++){
  doSomething(items[i]); 
}
// Impairment iteration  -- High efficiency 
for(var i = items.length - 1;i >= 0;i--){
  doSomething(items[i]); 
}

3.2 simplify termination conditions

Because each loop computes the termination condition, it must be executed as much as possible. The main point here is to avoid looking up other DOM elements and their attributes.


 // If you look at the termination condition, you need to query each loop items And its length attribute 
for(var i = 0;i < items.length;i++){
  doSomething(items[i]); 
}

// will items.length Is stored in a local variable lng In the. 
for(var i = 0,lng = items.length;i < lng;i++){
  doSomething(items[i]); 
}

3.3 simplify the circulation body

For reasons above and above, avoid a lot of intensive operations in the circulation.

This is actually the same as above: 1.1 minimize live updates. It's a kind of optimization. You can go back.

4. Basic algorithm optimization

In a computer, the complexity of the algorithm is expressed in O. Here are some common types of algorithms in javascript:

O(1) : constant, the execution time is constant regardless of the number of values, such as simple values and values stored in variables.
O(log n) : logarithm, the total execution time is related to the quantity, but not 1 must be obtained for each value, such as: 2 points search
O(n) : linear, the total execution time is directly related to the quantity, e.g., traversal
O(n*n) : square, total execution time is related to quantity, each value gets N at least times, e.g., insertion sort
ok, with the above knowledge, we can perform some algorithm optimization on javascript. Look at the code:


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

This code has performed four constant value searches: the number 5, the variable value, the number 10, and the variable sum. The algorithm complexity of this code is O(1). Such as:


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

Accessing array elements in javascript is also an O(1) operation, as is simple variable lookup efficiency. Then look at:


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

The point is that accessing properties on an object is less efficient than accessing arrays and variables. Because this is an O operation. You need to find the property in the prototype chain of the object, which takes a lot of time.

Well, after looking at this is not feeling in front of a piece of light ah. In fact, what we talked about before is to save the frequently used global property in a local variable according to this principle. Access to the global property is an operation of O(n), while access to the variable is an operation of O(1).

5. Minimize the number of statements

Most of the optimizations I've talked about are related to streamlining optimization statements. Yes, I think the quality and quantity of code is the criterion for performance. I've talked about some code quality-related optimizations, but I'll talk about code quantity optimizations.

5.1 simplify variable declarations


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

5.2 use arrays and object literals


var list = document.getElementById('mylist'),
      fragment = document.creatDocumentFragment(),
      item,
      i;
for(i = 0; i < 10; i++){
  item = document.creatElement('li');
  fragment .appendChild(item);
  item.appendChild(document.creatTextNode('item' + i));
}
list.appendChild(fragment);
1

6. Other

Write tired, if there is incorrect place please correct oh, there are 1 some other optimization, the next article continue!


Related articles: