Home > Web Front-end > JS Tutorial > Summary of JavaScript performance traps (with examples)_javascript skills

Summary of JavaScript performance traps (with examples)_javascript skills

WBOY
Release: 2016-05-16 18:13:10
Original
956 people have browsed it

1. Avoid using eval or Function constructor
2. Avoid using with
3. Do not use try-catch-finally in functions with critical performance requirements
4. Avoid using global variables
5. Avoid using for-in in functions with critical performance requirements
6. Use string accumulation calculation style
7. The original operation will be faster than the function call
8. Pass when setting setTimeout() and setInterval() Function names instead of strings
9. Avoid using unnecessary DOM references in objects
10. Clearest target speed, minimize scope chain
11. Try to use fewer comments in scripts , avoid using long variable names
12. Store external variables of the application in the current scope
13. Use variables to cache values ​​

1. Avoid using eval or Function constructors
Using eval or Function constructors is very expensive, requiring a script engine to convert source code to executable code every time.
Additionally, using eval to handle strings must be interpreted at runtime.

Code that runs slowly:

Copy the code The code is as follows:

function addMethod(object, property, code) {
object[property] = new Function(code);
}
addMethod(myObj, 'methodName', 'this.localVar=foo');

Code that runs faster:
Copy the code The code is as follows:

function addMethod(object, property, func) {
object[property] = func;
}
addMethod(myObj, 'methodName', function () { 'this.localVar=foo'; });

2. Avoid using with
Although very convenient, with requires additional search reference time because it does not know the upper and lower scope at compile time.

Code that runs slowly:
Copy the code The code is as follows:

with (test.object) {
foo = 'Value of foo property of object';
bar = 'Value of bar property of object';
}

runs faster Code:
Copy code The code is as follows:

var myObj = test.object;
myObj.foo = 'Value of foo property of object';
myObj.bar = 'Value of bar property of object'; Use try-catch-finally in a function
try-catch-finally will create a new variable in the current scope each time during runtime, which is used to allocate exceptions in statement execution.
Exception handling should be done at a high level in the script, where exceptions do not occur very frequently, such as outside a loop. If possible, try to avoid using try-catch-finally entirely.
Code that runs slowly:




Copy code
The 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 code
The 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 scope, the script engine needs to traverse the entire scope to find them.
Variables in the global scope exist throughout the life cycle of the script, and those in the local scope will be destroyed when the local scope is lost.
Code that runs slowly:




Copy code
The 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();


Code that runs faster:
Copy code The 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
for- in functions with critical performance requirements The in loop requires the script engine to build a list of all enumerable properties and check if they are duplicates of the previous ones.
If the code in your for loop scope does not modify the array, you can pre-calculate the length of the array and use it to iterate the array in the for loop.

Code that runs slowly:
Copy code The code is as follows:

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

Run faster code:
Copy code The code is as follows:

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

6. Use string accumulation calculation style
Using an operation creates a new string in memory and assigns the concatenated value to it. Just assign the result to a variable.
In order to avoid connecting the intermediate variables of the result, you can use = to directly assign the result.

Code that runs slowly:
Copy code The code is as follows:

a = 'x' 'y';

Run faster code:
Copy code Code As follows:

a = 'x'; a = 'y';

7. The original operation will be faster than the function call
Consider using alternative primitive operations in loops and functions where performance is critical.
Code that runs slowly:
Copy code The code is as follows:

var min = Math .min(a, b);
arr.push(val);

Run faster code:
Copy code The code is as follows:

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

8. When setting setTimeout() and setInterval(), pass the function name instead of a string
If you pass a string to setTimeout() or setInterval(), the string will It will be calculated by eval and cause slowness.
Use an anonymous function wrapper instead so it can be interpreted and optimized at compile time.

Code that runs slowly:
setInterval('doSomethingPeriodically()', 1000);
setTimeOut('doSomethingAfterFiveSeconds()', 5000);

Code that runs faster :
Copy code The code is as follows:

setInterval(doSomethingPeriodically, 1000);
setTimeOut (doSomethingAfterFiveSeconds, 5000);

9. Avoid using unnecessary DOM references in objects

Don’t do this:

Copy code The code is as follows:

var car = new Object();
car.color = " red";
car.type = "sedan"

A better form:

Copy code The code is as follows:

var car = {
color : "red";
type : "sedan"
}

10. Clearest target speed, minimize scope chain

Inefficient method:
Copy code The code is as follows:

var url = location.href;

An efficient form:
Copy code The code is as follows:

var url = window.location.href;

11. Try to use less comments in the script and avoid using long Variable names
should have as few comments as possible or avoid using them, especially in functions, loops and arrays.
Comments unnecessarily slow down script execution and increase file size. For example:

Not recommended form:

Copy code The code is as follows:

function someFunction()
{
var person_full_name="somename"; /* stores the full name*/
}

Better way of writing:
Copy code The code is as follows:

function someFunction()
{
var name= "somename";
}

12. Store the external variables of the application in the current scope
When a function is executed, the running context is passed, An active object will contain all local variables that will be pushed to the front of the context chain.
In the scope chain, the slowest ones are clearly identified identifiers, meaning local variables are the fastest. Reading and writing frequently used external variables will be significantly faster. This is especially noticeable for global variables and other deep identifier lookups.
Similarly, variables in the current scope (var myVar) are accessed faster than objects like properties (this.myVar).

Slow-running code:

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

Code that runs faster:

Copy the code The 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, it will be faster to use a local DOM access (such as get in the example).
Code that runs faster:
Copy code The code is as follows:

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

13. Use variables to cache values ​​
Use local variables to cache values ​​where repeated work is done.
The following set of examples illustrates the broad implications of storing values ​​into local variables.

Example 1. Use variables to store mathematical functions in the loop body before calculation execution
Wrong method:
Copy code The code is as follows:

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

Better processing:
Copy code The 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. Saving the length of the array using
in a loop. Poor processing:
The length of the array will be recalculated every time
Copy code The code is as follows:

for (var i = 0; i < arr.length; i ) {
// do something
}

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

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

Total Generally speaking, if it has been done once, we do not need to do unnecessary work repeatedly. For example, if the value of a calculated expression is used multiple times in a scope or function, saving it to a variable allows it to be used multiple times, otherwise we would overdo it by declaring a variable and assigning it a value that only applies once. So please keep these in mind.

Additional explanation:
Point 2
By the way, JS is not compiled but interpreted. Although it does not affect expression, it is better to be academically rigorous.

Point 6: Is this a messed up format?
a = 'x' 'y';
Run faster code:

a = 'x'; a = 'y';

9. Avoid using unnecessary DOM references in objects
Is new Object also a DOM reference?
This should mean that you should not use new Object() and new Array lightly. (), and new Function() generally use {...}, [...], f = function(..){...}, that is:
This should be the same as the above point. That's it.

Finally, I would like to add that you should use less bit operations, because all numerical operations in js (at the JS engine level) are all converted to floating point calculations... so bit operations may be slower. .
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template