Summary of JavaScript performance traps (for example)

Source: Internet
Author: User

1. Avoid using eval or Function Constructor
2. Avoid using
3. Do not use try-catch-finally in functions with performance requirements.
4. Avoid using global variables
5. Avoid using for-in functions with performance requirements.
6. Use string to accumulate the computing style
7. The original operation will be faster than the function call
8. When setTimeout () and setInterval () are set, the function name is passed instead of the string.
9. Avoid using unnecessary DOM references in objects
10. The clearest target speed minimizes the scope chain
11. Try to use less comments in the script to avoid using long variable names.
12. Store the application's external variables in the current scope
13. use variable cache values

1. Avoid using eval or Function Constructor
Constructing functions using eval or Function is very expensive. Every time, the script engine needs to convert the source code to executable code.
In addition, strings processed using eval must be interpreted at runtime.

Code that runs slowly:
Copy codeThe Code is as follows:
Function addMethod (object, property, code ){
Object [property] = new Function (code );
}
AddMethod (myObj, 'methodname', 'this. localVar = foo ');

Run faster code:
Copy codeThe Code is as follows:
Function addMethod (object, property, func ){
Object [property] = func;
}
AddMethod (myObj, 'methodname', function () {'this. localVar = foo ';});

2. Avoid using
Despite its convenience, with needs to append the search reference time because it does not know the upper and lower scopes during compilation.

Code that runs slowly:
Copy codeThe Code is as follows:
With (test. object ){
Foo = 'value of foo property of object ';
Bar = 'value of bar property of object ';
}

Run faster code:
Copy codeThe Code is as follows:
Var myObj = test. object;
MyObj. foo = 'value of foo property of object ';
MyObj. bar = 'value of bar property of object ';

3. Do not use try-catch-finally in functions with performance requirements.
Try-catch-finally creates a new variable in the current scope each time during the runtime to allocate exceptions for statement execution.
Exception Handling should be completed at the top of the script, where exceptions do not occur frequently, such as outside a loop body.
If possible, try to avoid using try-catch-finally.

Code that runs slowly:
Copy codeThe Code is as follows:
Var object = ['foo', 'bar'], I;
For (I = 0; I <object. length; I ++ ){
Try {
// Do something that throws an exception
} Catch (e ){
// Handle exception
}
}

Run faster code:
Copy codeThe Code is as follows:
Var object = ['foo', 'bar'], I;
Try {
For (I = 0; I <object. length; I ++ ){
// Do something
}
} Catch (e ){
// Handle exception
}

4. Avoid using global variables
If you use global variables in a function or other scopes, the script engine needs to traverse the entire scope to find them.
Variables in the global scope exist in the lifecycle of the script, and the local scope will be destroyed when the local scope is lost.

Code that runs slowly:
Copy codeThe Code is as follows:
Var I,
Str = '';
Function globalScope (){
For (I = 0; I <100; I ++ ){
Str + = I; // here we reference I and str in global scope which is slow
}
}
GlobalScope ();

Run faster code:
Copy codeThe Code is as follows:
Function localScope (){
Var I,
Str = '';
For (I = 0; I <100; I ++ ){
Str + = I; // I and str in local scope which is faster
}
}
LocalScope ();

5. Avoid using for-in functions with performance requirements.
The for-in loop requires the script engine to create a list of all enumeration attributes and check whether the list is repeated with the previous one.
If the code in the scope of your for loop does not modify the array, you can calculate the length of the array in advance to iterate the array in the for loop.

Code that runs slowly:
Copy codeThe Code is as follows:
Var sum = 0;
For (var I in arr ){
Sum + = arr [I];
}

Run faster code:
Copy codeThe Code is as follows:
Var sum = 0;
For (var I = 0, len = arr. length; I <len; I ++ ){
Sum + = arr [I];
}

6. Use string to accumulate the computing style
The + operation creates a new string in the memory and assigns the connected value to it. Only assign this result to a variable.
To avoid intermediate variables in the connection results, you can use + = to directly assign values to the results.

Code that runs slowly:
Copy codeThe Code is as follows:
A + = 'X' + 'y ';

Run faster code:
Copy codeThe Code is as follows:
A + = 'X'; a + = 'y ';

7. The original operation will be faster than the function call
You can consider using an alternative original operation in the loop and function with key performance requirements.
Code that runs slowly:
Copy codeThe Code is as follows:
Var min = Math. min (a, B );
Arr. push (val );

Run faster code:
Copy codeThe Code is as follows:
Var min = a <B? A: B;
Arr [arr. length] = val;

8. When setTimeout () and setInterval () are set, the function name is passed instead of the string.
If you pass a string to setTimeout () or setInterval (), the string will be calculated by eval and cause slowness.
Replace it with an anonymous function packaging so that it can be interpreted and optimized during compilation.

Code that runs slowly:
SetInterval ('dosomethingperiodically () ', 1000 );
SetTimeOut ('dosomethingafterfiveseconds () ', 5000 );

Run faster code:
Copy codeThe Code is as follows:
SetInterval (maid, 1000 );
SetTimeOut (doSomethingAfterFiveSeconds, 5000 );

9. Avoid using unnecessary DOM references in objects

Do not do this:

Copy codeThe Code is as follows:
Var car = new Object ();
Car. color = "red ";
Car. type = "sedan"

A better form:

Copy codeThe Code is as follows:
Var car = {
Color: "red ";
Type: "sedan"
}

10. The clearest target speed minimizes the scope chain

Inefficiency:
Copy codeThe Code is as follows:
Var url = location. href;

An efficient form:
Copy codeThe Code is as follows:
Var url = window. location. href;

11. Try to use less comments in the script to avoid using long variable names.
Minimize comments or avoid comments, especially in functions, loops, and arrays.
Note unnecessary slowing down script execution and increasing the file size. For example:

Not recommended form:

Copy codeThe Code is as follows:
Function someFunction ()
{
Var person_full_name = "somename";/* stores the full name */
}

Better Syntax:
Copy codeThe Code is as follows:
Function someFunction ()
{
Var name = "somename ";
}

12. Store the application's external variables in the current scope
When a function is executed to run upstream and downstream queries, an active object contains all local variables and is pushed to the front of the context chain.
In the scope chain, the slowest is a clear identifier, which means that local variables are the fastest. Reading and writing of frequently used external variables will be significantly accelerated. This is especially evident in searching for global variables and other deep identifiers.
Similarly, the variable (var myVar) in the current scope is faster than the object image attribute (this. myVar ).

Code that runs slowly:

Copy codeThe Code is as follows:
Function doSomething (text ){
Var divs = document. getElementsByTagName ('div '),
Text = ['foo',/*... n... */, 'bar'];
For (var I = 0, l = divs. length; I <l; I ++ ){
Divs [I]. innerHTML = text [I];
}
}

Run faster code:

Copy codeThe Code is as follows:
Function doSomethingFaster (text ){
Var doc = document,
Divs = doc. getElementsByTagName ('div '),
Text = ['foo',/*... n... */, 'bar'];
For (var I = 0, l = divs. length; I <l; I ++ ){
Divs [I]. innerHTML = text [I];
}
}

If you need to access an element (such as head) in a large loop, using a local DOM (such as get in the example) will be faster.
Run faster code:
Copy codeThe Code is as follows:
Function doSomethingElseFaster (){
Var get = document. getElementsByTagName;
For (var I = 0, I <100000; I ++ ){
Get ('head ');
}
}

13. use variable cache values
Use the local variable cache value for repetitive work.
The following examples demonstrate the wide significance of storing values to local variables.

Example 1. Use variables to store mathematical functions in a loop before computing execution
Incorrect method:
Copy codeThe Code is as follows:
Var d = 35;
For (var I = 0; I <1000; I ++ ){
Y + = Math. sin (d) * 10;
}

Better Processing:
Copy codeThe Code is as follows:
Var d = 55;
Var math_sind = Math. sin (d) * 10;
For (var I = 0; I <1000; I ++ ){
Y + = math_sind;
}

Example 2. Save the array length in a loop
Poor processing:
The length of the array is calculated repeatedly each time.
Copy codeThe Code is as follows:
For (var I = 0; I <arr. length; I ++ ){
// Do something
}

Better improvements:
A better way is to save the length of the array.
Copy codeThe Code is as follows:
For (var I = 0, len = arr. length; I <len; I ++ ){
// Do something
}

In general, if we have already done this once, we do not need to repeat the unnecessary work. For example, if the scope or function uses the value of a calculated expression multiple times and saves it to a variable, it can be used multiple times, otherwise, we will overhead a variable, assign a value, and apply it only once. So remember this.

Note:
2nd o'clock
By the way, JS mainly does not compile and explain. Although it does not affect the expression, it is still academic and rigorous.

At, is the format messy?
A + = 'X' + 'y ';
Run faster code:

A + = 'X'; a + = 'y ';

9. Avoid using unnecessary DOM references in objects
Is new Object referenced by DOM?
This should be to say that you should not use new Object () or new Array (), and new Function () in general {...}, [...], f = function (..) {...} that is:
This is the same as what we should say above.

At last, I added a bitwise operation, because all the numeric operations in js (to the JS engine layer) are finally converted to floating point calculations, so bitwise operations may be slower.

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.