How to improve javascript code performance _ javascript skills

Source: Internet
Author: User
In web applications, a large amount of Javascript is applied, so code execution efficiency becomes particularly important, that is, performance! To improve JS performance, we should master some basic performance optimization methods and make them the habit of writing code. The following describes several ways to optimize performance. many beginners and even experienced developers will ignore this article. I hope it will help you to summarize this article on code performance after you write the maintainability code article, after several days of delay, I decided to update an article every day, because I had to owe too many things and did not sum up the things I had learned. I forgot it very quickly, record what impressed you with your mental power, especially the maintainability code, performance, and so on. when a habit is formed in your mind, you will be awesome! Here we also want to give a beginner's suggestion: sum up what you have learned, because it is actually learning new knowledge! Well, let's go to our topic: how to improve the performance of JS code.

1. optimize DOM interaction

DOM is closely related to our pages. browsers render pages, that is, DOM elements after rendering and parsing. DOM operations and interaction consume a lot of time, because they often need to re-render the entire page or a part. Further, some seemingly subtle operations may take a lot of time to execute. because DOM has a lot of information to process, we should optimize DOM-related operations as much as possible, speed up page rendering by the browser! Why does some DOM operations affect page performance? please refer to my article on browser principles:

OK to optimize DOM operations. There are several methods:

1.1 minimal on-site update

What is DOM onsite update: you need to update the display of a part of the page already displayed in the DOM part immediately. However, each change, whether it is inserting a single character or a whole segment, has a certain performance penalty, because the browser needs to re-calculate numerous sizes for updates (please read the relevant knowledge :). Therefore, the more on-site updates, the longer the code execution time, and the faster the code execution, as shown below:

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 projects to the list mylist. If no project is added, two on-site updates are required: 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 slowly.

The solution is to use document fragments 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 requires only one on-site update. Remember, when you pass in the file fragment to appendChild (), only the child nodes in the file fragment will be added to the target element, and the fragment itself will not be added.

Now, you should understand how sorry you are for the browser to directly add, query, modify, and delete DOM nodes in a loop )′.

1.2 use innerHTML

In addition to using creatElement () and appendChild () in the code above to create DOM elements, you can also assign values to innerHTML. For small DOM changes, the efficiency of the two methods is almost the same, but for a large number of DOM node changes, the latter is much faster than the former! Why?

Because when we assign a value to innerHTML, an HTML parser will be created in the background, and an internal DOM call will be used to create a DOM structure instead of Javascript-based DOM call, since the internal method is compiled rather than interpreted for execution, the code execution speed is much faster!

Use innerHTML to rewrite the above example:

Var list = document. getElementById ('mylist'), html = '', // declare an empty string I; for (I = 0; I <10; I ++) {html + ='
  • Item '+ I +'
  • ';} List. innerHTML = html; // Remember that the four letters of HTML after innerHTML must be capitalized!

    This method also only performs on-site updates once, and the performance is better than the previous method! Although there is a little performance loss on the string link.

    1.3 Use event proxy/event delegate

    Event handlers provide interaction capabilities for web applications. Therefore, many developers add a large number of processing programs to pages without authorization, the problem is that the number of event handlers on a page is directly related to the overall running performance of the page. Why pinch?

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

    Second, we must specify all event handlers in advance, which leads to an increase in DOM access times, which will delay the interaction readiness of the entire page and slow page response to user operations.

    So reducing event handlers can also make our pages more smooth! Event delegate token!

    The principle of event delegation is actually event bubbling. you can specify only one event handler to manage all events of a certain type of operation. For example, the click event will always bubble to the document level. that is to say, we do not need to add events to each element. we only need to add an event handler to the element at a higher level, then, the attribute or method of the event object is used to determine the elements of the current click and then respond accordingly. I will not talk about this. beginners can learn about event bubbling on their own.

    2. scope is very important

    When it comes to scope, it is easy to think of scope chain. we know that to search for a variable, the execution environment where the variable is located must search for the variable along this scope, there are a lot of variables on the scope chain, so we have to traverse, traversal takes time, and the more time you need to look up, if we can reduce this time, can we improve the code execution efficiency?

    So smart, OK. Let me see which methods can reduce this time:

    2.1 avoid global search

    This is an important part of Performance Optimization. as mentioned above, the more time it takes to look up, the more global variables and functions are to be searched! Check 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 often did this before. However, we can find that this code references the global variable document in three places. if there are many images on our page, the document in the for loop will be executed hundreds of times, every time, you need to search in the scope chain, where is the time? I have not ...... stop !.

    We can create a local variable in the function to save the reference to the document. in this way, we do not need to go to the global variable to reference the document anywhere in the function. This improves the code performance. check the code:

    Function updateUI () {var doc = document; // save the document in the local variable doc 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 global variables are often used in functions, save them in local variables!

    2.2 avoid using with statements

    The with statement is used to extend the scope. it is also time-consuming to search for variables. this is generally not used, so it is not expanded. The solution is to save the global variables in the local variables like the above example!

    3. optimized cycle

    Loop programming is a common practice. It can also be seen everywhere in js. The Loop has repeatedly executed the same piece of code, and the execution time has been accumulated, therefore, the execution time can be greatly reduced by optimizing the code of the loop body! How to optimize it? Four methods.

    3.1 impairment iteration

    When we write the iterator (cyclic condition), we usually do this (var I = 0; I <10; I ++), starting from 0 and increasing to a specific value. However, in many cases, it is more efficient to use the impairment iterator in a loop. I tested it. if the loop body is not complex, the two are similar!

    // Value-added 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 simplified termination conditions

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

    // Depending on the termination condition, you need to query items and its length attribute for (var I = 0; I <items. length; I ++) {doSomething (items [I]);} // Set items. the length value is stored in the local variable lng. For (var I = 0, lng = items. length; I <lng; I ++) {doSomething (items [I]);}

    3.3 simplified loop body

    The reason is similar to the above, so a large number of intensive operations are avoided in the circular body.

    This is actually the same as the above: 1.1 minimized on-site updates. Is the same optimization method. You can go back and check it out.

    4. basic algorithm optimization

    In computers, the complexity of algorithms is represented by O. Below are several common algorithm types in javascript:

    O (1): constant, regardless of the number of values, the execution time is constant, such as the simple value and the value stored in the variable.
    O (log n): Logarithm. the total execution time is related to the number, but it is not necessary to obtain each value, for example, binary search.
    O (n): Linear. the total execution time and quantity are directly related, for example, traversal.
    O (n * n): Square. the total execution time is related to the quantity. each value must be obtained at least N times, for example, insert sorting.
    OK. with the above knowledge, we can optimize some algorithms for javascript. Check the code:

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

    This code performs four constant value searches: 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 the array element in javascript is also an O (1) operation, which is the same as searching simple variables. Let's look at it again:

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

    The attribute on the access object is less efficient than accessing arrays and variables. This is an O (n) operation. You need to search for this attribute in the prototype chain of the object, which takes a lot of time.

    Well, after reading this, does it feel bright. In fact, according to this principle, we have to save frequently used global attributes in a local variable. accessing global attributes is an O (n) operation, the access variable is an O (1) operation. tell me which excavator is strong!

    5. minimize the number of statements

    The optimization mentioned above is basically related to the simplified optimization statement. Yes, I think the quality and quantity of the code are the criteria for judging the performance. I have discussed some optimization related to code quality. here I will talk about the optimization of code quantity.

    5.1 simplified variable declaration

    // Five statements are used to declare five variables var count = 5; var color = 'red'; var values = [1, 2, 3]; var now = new Date (); // five variables are declared using one statement. Note that each variable is separated by commas (,). var count = 5, color = 'red', values = [, 3]. now = new Date ();

    5.2 Use array and object literal

    // Create two objects ---- bad method // one statement var values = new Array (); values [0] = 123; values [1] = 456; values [2] = 789; // two statement var person = new Object (); person. name = 'job'; person. age = 21; person. sayName = function () {alert (this. name) ;}; // create two objects ---- recommended method // one statement var values = [123,456,789] // two 1 statement var person = {name: 'job', age: 21, sayName: function () {alert (this. name );};

    6. Miscellaneous

    I am tired of writing. please correct me if there are any errors. there are some other optimizations. continue to the next article!

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.