A summary of JavaScript performance traps (illustrated with examples) _javascript tips

Source: Internet
Author: User
Tags exception handling mathematical functions setinterval sin
1. Avoid using eval or function constructors
2. Avoid using with
3. Do not use try-catch-finally in functions that are critical to performance requirements
4. Avoid using global variables
5. Avoid using for-in in functions that are critical to performance requirements
6. Use a string to add a calculation style
7. The original operation will be faster than the function call
8. Pass function name instead of string when setting settimeout () and SetInterval ()
9. Avoid using unwanted DOM references in objects
10. The clearest target speed, minimize the scope of the chain
11. Try to use fewer annotations in your script to avoid using long variable names
12. External variables applied in the current scope store
13. Using Variable cache values

1. Avoid using eval or function constructors
The cost of using eval or function constructors is very expensive, requiring the scripting engine to transform source code to executable code each time.
In addition, using the eval processing string must be interpreted at run time.

Slow-Running code:
Copy Code code as follows:

function Addmethod (object, property, code) {
Object[property] = new Function (code);
}
Addmethod (myobj, ' methodname ', ' This.localvar=foo ');

To run faster code:
Copy Code code as follows:

function Addmethod (object, property, func) {
Object[property] = func;
}
Addmethod (myobj, ' methodname ', function () {' This.localvar=foo ';});

2. Avoid using with
Although convenient, with the need for additional lookup reference time, because it does not know the scope of the upper and lower at compile time.

Slow-Running code:
Copy Code code as follows:

With (Test.object) {
Foo = ' Value of foo ' of object ';
Bar = ' Value of Bar property of object ';
}

To run faster code:
Copy Code code as follows:

var myobj = Test.object;
Myobj.foo = ' Value of foo ' of object ';
Myobj.bar = ' Value of Bar property of object ';

3. Do not use try-catch-finally in functions that are critical to performance requirements
Try-catch-finally creates a new variable in the current scope each time at run time to assign the exception that the statement executes.
Exception handling should be done at the top of the script, where the exception is not very frequent, such as the outside of a loop body.
If possible, try to avoid using try-catch-finally altogether.

Slow-Running code:
Copy Code code as follows:

var object = [' foo ', ' Bar '], I;
for (i = 0; i < object.length; i++) {
try {
Do something this throws an exception
catch (e) {
Handle exception
}
}

To run faster code:
Copy Code code 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 scope, the scripting engine needs to traverse the entire scope to find them.
Variables in the global scope are present in the life cycle of the script, and the local scope is destroyed when the local scope is lost.

Slow-Running code:
Copy Code code as follows:

var i,
str = ';
function Globalscope () {
for (i=0 i < i++) {
str = i; Here we reference I and STR into global scope which is slow
}
}
Globalscope ();

To run faster code:
Copy Code code as follows:

function Localscope () {
var i,
str = ';
for (i=0 i < i++) {
str = i; I and STR in the local scope which is faster
}
}
Localscope ();

5. Avoid using for-in in functions that are critical to performance requirements
The for-in loop requires the scripting engine to create a list of all enumerable properties and check whether it is duplicated with the previous one.
If the code in your for loop scope does not modify the array, you can calculate the length of the array in advance to iterate over the group in the For Loop.

Slow-Running code:
Copy Code code as follows:

var sum = 0;
for (var i in arr) {
Sum + + arr[i];
}

To run faster code:
Copy Code code as follows:

var sum = 0;
for (var i = 0, len = arr.length i < len; i++) {
Sum + + arr[i];
}

6. Use a string to add a calculation style
Using the + operation creates a new string in memory and assigns the value of the connection to it. Just assign the result to a variable.
To avoid the intermediate variables of the connection result, you can use + + to directly assign the result.

Slow-Running code:
Copy Code code as follows:

A + + ' x ' + ' Y ';

To run faster code:
Copy Code code as follows:

A = = ' x '; A + = ' y ';

7. The original operation will be faster than the function call
Consider the use of the original action that can be substituted in the loop and function that are critical to performance requirements.
Slow-Running code:
Copy Code code as follows:

var min = Math.min (A, b);
Arr.push (Val);

To run faster code:
Copy Code code as follows:

var min = a < b? A:B;
Arr[arr.length] = val;

8. Pass function name instead of string when setting settimeout () and setinterval ()
If you pass a string to settimeout () or setinterval (), the string will be evaluated slowly by Eval.
Use an anonymous function wrapper to replace it so that it can be interpreted and optimized at compile time.

Slow-Running code:
SetInterval (' dosomethingperiodically () ', 1000);
SetTimeout (' Dosomethingafterfiveseconds () ', 5000);

To run faster code:
Copy Code code as follows:

SetInterval (dosomethingperiodically, 1000);
SetTimeout (Dosomethingafterfiveseconds, 5000);

9. Avoid using unwanted DOM references in objects

Don't do this:

Copy Code code as follows:

var car = new Object ();
Car.color = "Red";
Car.type = "Sedan"

A better form:

Copy Code code as follows:

var car = {
Color: "Red";
Type: "Sedan"
}

10. The clearest target speed, minimize the scope of the chain

Low efficiency methods:
Copy Code code as follows:

var url = location.href;

An efficient form:
Copy Code code as follows:

var url = window.location.href;

11. Try to use fewer annotations in your script to avoid using long variable names
Make as few comments as possible or avoid using annotations, especially in functions, loops, and arrays.
Note Unnecessary mitigation of script execution and increased file size. Like what:

Not recommended in the form of:

Copy Code code as follows:

function SomeFunction ()
{
var person_full_name= "Somename"; /* Stores the full name*/
}

Better way to do it:
Copy Code code as follows:

function SomeFunction ()
{
var name= "Somename";
}

12. External variables applied in the current scope store
When a function is executed running up and down and asking for a piece, an active object that contains all the local variables is pushed to the front of the context chain.
In the scope chain, the slowest is the clear identifier, which means that the local variable is the fastest. Both read and write external variables that are frequently used by storage are significantly faster. This is particularly noticeable for global variables and other deep-seated identifier lookups.
Similarly, a variable (var myVar) in the current scope is faster (This.myvar) than an object-like property.

Slow-Running code:

Copy Code code 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];
}
}

To run faster code:

Copy Code code 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 access to an element (such as head) in a large loop, using a local DOM access (e.g., get in the example) is faster.
To run faster code:
Copy Code code as follows:

function Dosomethingelsefaster () {
var get = document.getElementsByTagName;
for (var i = 0, i < 100000; i++) {
Get (' head ');
}
}

13. Using Variable cache values
Use local variables to cache values where you do repetitive work.
The following set of examples shows the broad significance of storing values to local variables.

Example 1. To use variables to store mathematical functions in a loop before performing a calculation
The wrong way:
Copy Code code as follows:

var d=35;
for (var i=0; i<1000; i++) {
Y + + Math.sin (d) *10;
}

Better handling:
Copy Code code as follows:

var d = 55;
var math_sind = Math.sin (d) *10;
for (var i=0; i<1000; i++) {
Y + + math_sind;
}

Example 2. The length of the saved array is used in loops
Bad treatment:
The length of the array will be repeated every time
Copy Code code as follows:

for (var i = 0; i < arr.length; i++) {
Do something
}

Better improvements:
The better way is to save the length of the array
Copy Code code as follows:

for (var i = 0, len = arr.length i < len; i++) {
Do something
}

In general, if you have done it once, we do not need to repeat the unnecessary work. For example, the value of an expression that is used more than once in a scope or function is saved to a variable so that it can be used more than once, otherwise we'll overdo it by declaring a variable and assigning it and then applying it only once. So please keep that in mind.

Supplementary Note:
2nd
By the way, JS is mainly not compiled to explain. Although it does not affect the expression, but academic or rigorous point good.

6th is this format messed up?
A + + ' x ' + ' Y ';
To run faster code:

A = = ' x '; A + = ' y ';

9. Avoid using unwanted DOM references in objects
Is the new object also a DOM reference?
This should mean not to use the new Object () and the new Array () as well as the new Function () generally using {...}, [...], F = Function (..) {...} That
This is one thing that should be said in the above.

Finally add a little bit operation, because JS all the numerical operations (to the JS engine this layer) are all transferred floating point to calculate. So bit operations may be slower.
Related 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.