Write better code

Because js was originally an interpreted language, the execution speed is much slower than that of compiled languages. Chrome is the first browser with a built-in optimization engine that compiles js into native code. Since then, the main browsers
have followed suit and successively realized the compilation and execution of js. Even in the new stage of compiling and executing js, there will still be inefficient code. Still, there are ways to improve the overall performance
of your code

Avoid global lookups
As the number of scopes increases, so does the time to access variables outside the current scope. Accessing global variables is always slower than accessing local variables because of the need to traverse the scope chain.

function updataUI(){
    var imgs = document.getElementsByTagName('img');
    for(var i=0,len=imgs.length; i<len; i++){
        imgs[i].title = document.title + 'images' + i;
    }
    var msg = document.getElementById('msg');
    msg.innerHTML = 'Update complete';
}

Contains three references to the global document object. If there are multiple images on the page, the document reference in the for loop will be executed many times or even hundreds of times, and
a scope chain lookup will be performed each time. Usually creating a local variable that points to the document object can be limited to improve the performance of this function.

function updataUI(){
    var doc = document;
    var imgs = doc.getElementsByTagName('img');
    for(var i=0,len=imgs.length; i<len; i++){
        imgs[i].title = doc.title + 'images' + i;
    }
    var msg = doc.getElementById('msg');
    msg.innerHTML = 'Update complete';
}

It's always a good idea to store global objects that are used multiple times in a function as local variables.

 

Avoid unnecessary attribute lookups
1, O(1) means constant value, no matter how many values ​​there are, it takes the same time to get the constant value. Getting constant values ​​is a very efficient process

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

The code does four constant value lookups: the number 5, the variable value, the number 10, and the variable sum. The overall complexity of this code is considered O(1)

2. Accessing arrays in js is also an O(1) operation, which is as efficient as simple variable lookup

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

3. Using variables and arrays is more efficient than accessing properties on objects, which is an O(n) operation. Any property lookup on an object will take longer than accessing a variable or array because
a search must be made in the prototype chain for the property with that name pair. In short, the more property lookups, the longer the execution time.

var values = {first:5, second:10};
var sum = values.first + values.second;
alert(sum);

This code uses two attribute lookups to compute the sum pair value. Doing an attribute lookup once or twice won't cause significant performance issues, but doing it hundreds or thousands will definitely slow down execution.

var query = window.location.href.substring(window.location.href.indexOf('?'));

In this code, there are 6 property lookups: 3 for window.location.href.substring() and 3 for window.location.href.indexOf().
The number of attribute lookups can be determined by simply counting the number of points of the code.

var url = window.location.href;
var query = url.substring(url.indexOf('?'));

This version of the code has only 4 property lookups, a 33% savings over the original version;

 

optimization loop

for(var i=0; i<values.length; i++){
    process(values[i]);
}

In this code the variable i is incremented from 0 to the total number of elements in the values ​​array. Assuming that the order in which the values ​​are processed doesn't matter, then the loop changes to i decrement

for(var i=values.length; i>=0; i--){
    process(values[i]);
}

Here, the variable i is decremented by 1 after each loop. In the process, the termination condition is reduced from an O(n) call of value.length to an O(l) call of 0. Since there is only one statement in the loop body
, no further optimization can be performed, but the loop can be changed to a post-test loop.

var i=values.length - 1;
if(i > -1){
   do{
       process(value[i])
   }while(--i >= 0);
}    

The main optimization here is to combine the termination condition and the decrement operator into a single statement. Remember when using the 'post-test' loop you must ensure that there is at least one value to be processed. An empty array would result in an extra
loop that the 'pre-test' loop can avoid.

Unrolling Loops
When the number of loops is deterministic, it is often faster to eliminate the loop and use multiple function calls.

for(var i=3; i>=0; i++){
    process(value[i]);
}

change to

process(value[0]);
process(value[1]);
process(value[2]);

Unrolling the loop in this way removes the overhead of setting up the loop and handling the termination condition


4. Avoid Double Interpretation

eval('alert("hello world !")');
setTimeout('alert("hello world !")',500);

In the above examples, the string containing the js code must be parsed. This operation cannot be completed during the initial parsing process, because the code is contained in a string, that is, when the js code runs,
a new parsing code must be started.

alert('hello world !');
setTimeout(function(){
    alert('hello world !');
},500)

If you want to improve code performance, try to avoid strings that need to be interpreted according to js.

 

The native method is faster
. The native method is written in a compiled language such as c/c++, so it is much faster than js. The most easily forgotten thing in js is that complex mathematical operations can be found in the math object. These method is much faster than
any same method written in js like sine, cosine


Multiple variable declarations

// 4 statements - wasteful 
var count = 5 ;
 var color = 'blue' ;
 var values ​​= [1,2,3 ];
 var now = new Date();

The number of multiple statements in the js code also affects the speed of the multiple operations performed. A single statement that completes multiple operations is faster than multiple statements that complete a single operation. Therefore, it is necessary to find statements that can be combined together
to reduce the execution time of the script.

var count = 5, color = 'blue', values = [1,2,3], now = new Date();

Here, the variable declaration uses only one var statement, separated by commas. This optimization is very easy to do in most cases and is much faster than a single variable declaration

 

Working with arrays and object literals

// Create and initialize array with 4 statements - waste of 
var values ​​= new Array();
values[0] = 123;
values[1] = 456;
values[2] = 789;
// Create and initialize array with 4 statements - waste 
var person = new Object();
person.name = 'Nicholas';
person.age = 29;
person.sayName = function(){
    alert(this.name);
}

In this code, only an array and an object are created and initialized. 4 statements are used each: one calls the constructor, the other 3 allocate data,

// Create and initialize array with 1 statement 
var values ​​= [123,456,789 ];


// Create and initialize object with 1 statement 
var person = {
    name: 'Nicholas',
    age: 29,
    sayName: function(){
        alert(this.name);
    }
}

The rewritten code contains only two statements, one to create and initialize the array, and one to create and initialize the object. What used to be eight statements before is now only used two, which reduces 75% of
the tens of thousands of lines of js. The value of these optimizations is even greater.


Optimize dom
1. Minimize field updates
createDocumentFragment() creates a virtual node object, or, in other words, is used to create document fragment nodes. It can contain various types of nodes and is empty at the beginning of creation

var list = document.getElementById('myList'),item,i;
for(i=0; i<10; i++){
    item = document.createElement('li');
    list.appendChild(item);
    item.appendChild(document.createTextNode('item'+i));
}

This code adds 10 items to the list. As each item is added, there are 2 live updates: one adds the <li> element, and the other adds a text node to it. Add 10 items like this, this operation completes a total of
20 live updates

var list = document.getElementById('myList'),item,i,
fragment = document.createDocumentFragment();

for(i=0; i<10; i++){
    item = document.createElement('li');
    fragment.appendChild(item);
    item.appendChild(document.createTextNode('item'+i));
}
list.appendChild(fragment);

There is only one live update in this example, and it happens after all projects have been created. The document fragment acts as a temporary placeholder for newly created items. Then use appendChild() to add all
items to the list. Remember, when passing a document fragment to appendChild(), only the child nodes in the fragment are added to the target, not the fragment itself.

2. Use innerHTML
When innerHTML is set to a certain value, an HTML parser will be created in the background, and then the internal DOM call is used to create the DOM structure instead of js-based DOM calls. Since the internal method is compiled
rather than interpreted, the execution is much faster.

var list = document.getElementById('myList'),i;
for(i=0; i<10; i++){
    list.innerHTML += '<li>item'+i+'</li>';
}

The key to using innerhtml is to minimize the number of times it is called

var list = document.getElementById('myList'),i,html='';
for(i=0; i<10; i++){
    html += '<li>item'+i+'</li>';
}
list.innerHTML = html;

This code builds an html string, then assigns it to list.innerHTML, which creates the DOM structure required.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324859051&siteId=291194637