Optimize the performance of JavaScript scripts

Source: Internet
Author: User

With the development of the network, network speed and machine speed, more and more websites use a variety of client technologies. Ajax is currently the most popular method. Javascript is an interpreted language, so it cannot reach the level of C/Java, which limits what it can do on the client. In order to improve its performance, I want to talk about my experience based on the many tests I have done for JavaScript before, hoping to help you improve your Javascript script performance.

Language Level Loop

Loop is a very common control structure, and most of the things need to be completed by it. In JavaScript, we can useFor (;), while (), for (in)In factFor (in)The efficiency is very poor, because he needs to query hash keys, as long as it can be used as little as possible.For (;;)AndWhileThe performance of cycle loops should be basically equivalent (usually used.

In fact, how to use these two cycles is very important. For some interesting cases during the test, see the appendix. The final conclusion is:

    • If it is a loop variable that increments or decreases, do not assign values to the loop variable separately. You should use nested++Or--Operator.

    • If you want to compare the length of the array, you should first put the Length attribute of the array into a local variable to reduce the number of queries.

For example, if arr is an array, the best way to traverse elements is:

 
For (VAR I = 0, Len = arr. length; I <Len; I ++ ){...}

Or, if there is no order:

 
For (VAR I = arr. length; I> 0; I --){...}
Local and global variables

Local variables are faster than global variables, because global variables are actually members of global objects, and local variables are placed in the function stack.

Do not use eval

UseEvalIt is equivalent to calling the interpretation engine again at runtime to run the content, which consumes a lot of time. At this time, the closure supported by javascript can be used to implement the function template (for details about the closure, refer to the relevant content of functional programming)

Reduce Object Search

Because Javascript is interpretedA. B. C. D. E, You need to perform at least four query operations, first check a and then check B in A, then check C in B, so proceed. So if such expressions repeat, you should try to avoid such expressions as long as possible. You can use local variables to put them in a temporary place for query.

This can be combined with loops, because we often need to loop based on the length of strings and arrays, And the length is usually unchanged, for example, each queryA. Length, An additional operation is required.VaR
Len = A. Length
, Then a query is missing.

String connection

If it is an append string, it is best to useS + = anotherstrOperation instead of usingS = S + anotherstr.

To connect multiple strings, use less + =, as shown in figure

 
S + =;

S + = B;

S + = C;

It should be written

 
S + = A + B + C;

If it is to collect strings, for example, to perform the + = operation on the same string multiple times, it is best to use a cache. How to use it? Use JavaScript Arrays for collection, and connect using the join method, as shown below:

VaR Buf = new array ();

For (VAR I = 0; I <100; I ++ ){

Buf. Push (I. tostring ());

}

VaR all = Buf. Join ("");
Type conversion

Type conversion is a common mistake because Javascript is a dynamic type language and you cannot specify the type of a variable.

1.
Converts a number to a string and applies it."" + 1Although it looks ugly, but in fact this efficiency is the highest, performance:

("" +)> String ()>. tostring ()> New String ()

This is actually a bit similar to the following "Direct Volume". The internal operations that can be used during compilation are faster than those used during running.

String ()Is an internal function, so the speed is very fast, and. Tostring ()To query the number of functions in the prototype, the speed is inferior,New String ()Returns an exact copy.

2.
Converting a floating point to an integer is more prone to errors.Parseint ()In factParseint ()Is used to convert a string to a number, instead of converting between a floating point and an integer. We should useMath. Floor ()OrMath. Round ().

In addition, the problem is different from that in the object search in section 2,MathIs an internal object, soMath. Floor ()In fact, there is not much query method and call time, and the speed is the fastest.

3.
For custom objects, ifTostring ()Explicit call is recommended for type conversion.Tostring ()Because the internal operation will try to convert the tostring () method of the object to string after trying all possibilities, it is more efficient to directly call this method.

Direct usage

In fact, this effect is relatively small and can be ignored. What is direct usage? For example, JavaScript supports[Param,...]In the past, we used to directly express an array.New array (Param, Param ,...)The former is directly explained by the engine, and the latter callsArrayInternal constructor, so it is a little faster.

Similarly,VaR Foo = {}The method is similarVaR Foo = new object ();Fast,VaR Reg = /../;Aspect RatioVaR Reg = new Regexp ()Fast.

String Traversal

Regular expressions should be used for loop operations on strings, such as replacement and search, because JavaScript itself is slow in the cycle, while regular expression operations are performed using APIs written in C language, good performance.

Advanced object

Custom advanced object andDate,RegexpObjects consume a lot of time during construction. If reusable, cache should be used.

Dom-related HTML insertion

Many users prefer to use it in JavaScript.Document. WriteTo generate content for the page. In fact, this is less efficient. If you need to insert HTML directly, you can find a container element, such as specifying a div or span, and set theirInnerhtmlTo convert your HTMLCodeInsert to the page.

Object Query

Use[""]Query Ratio. Items ()Faster, which is the same as the previous idea of reducing object search.. Items ()Added a query and function call.

Create a DOM Node

Generally, we may use strings to directly write HTML to create nodes.

    1. Code validity cannot be guaranteed

    2. Low string operation efficiency

So it should be usedDocument. createelement ()Method. If there is a ready-made template node in the documentClonenode ()Method becauseCreateelement ()After the method, you need to set the attributes of multiple elements, useClonenode ()You can reduce the number of attribute settings-if you need to create many elements, you should first prepare a template node.

Timer

If the code is continuously running, you should not useSetTimeoutInsteadSetinterval.SetTimeoutReset a timer every time.

Other script Engines

According to my test, Microsoft's JScript is much less efficient than Mozilla's spidermonkey, whether it is execution speed or memory management, because JScript is not updated now. But spidermonkey cannot be used.Activexobject

File Optimization

File optimization is also an effective method. Deleting all spaces and comments and placing the code in one line can speed up the download process. Note that the download speed is not the resolution speed, if it is local, comments and spaces do not affect the speed of interpretation and execution.

Summary

This article summarizes some methods I have found in JavaScript programming to improve the Javascript running performance. In fact, these experiences are based on several principles:

    1. Taking the ready-made items directly is faster, for example, local variables are faster than global variables, and the direct amount is faster than the constructed object at runtime.

    2. Reduce execution times as little as possible. For example, You Need To Cache multiple queries first.

    3. Try to use the built-in functions of the language, such as string link.

    4. Use the APIS provided by the system as much as possible because these APIs are compiled binary code with high execution efficiency.

At the same time, some basicAlgorithmThe optimization can also be used in Javascript, such as the adjustment of the operation structure. However, JavaScript is interpreted and generally does not optimize bytecode during runtime. Therefore, these optimizations are still very important.

Of course, some of the skills here are also used in other explanatory languages for your reference.

Reference
    • Test and comparison of various http://www.umsu.de/jsperf/ browsers

    • Http://home.earthlink.net /~ Kendrasg/INFO/js_opt/

Appendix 1

The test code is incomplete due to previous tests. I have added the following parts:

VaR print;



If (typeof document! = "Undefined "){

Print = function (){

Document. Write (arguments [0]);

}

} Else if (typeof wscript! = "Undefined "){

Print = function (){

Wscript. Echo (arguments [0], arguments [1], arguments [2]);

}

}



Function empty (){

}



Function benchmark (f ){

VaR I = 0;

VaR start = (new date (). gettime ();



While (I <pressure ){

F (I ++ );

}

VaR end = (new date (). gettime ();

Wscript. Echo (end-Start );

}



/*

I = 0

Start = (new date (). gettime ();

While (I <60000 ){

C = [I, I];

I ++;

}

End = (new date (). gettime ();

Wscript. Echo (end-Start );

I = 0

Start = (new date (). gettime ();

While (I <60000 ){

C = new array (I, I );

I ++;

}

VaR end = (new date (). gettime ();

Wscript. Echo (end-Start );

*/



Function interncast (I ){

Return "" + I;

}



Function stringcast (I ){

Return string (I)

}

Function newstringcast (I ){

Return new string (I)

}

Function tostringcast (I ){

Return I. tostring ();

}

Function parseint (){

Return parseint (j );

}

Function mathfloor (){

Return math. Floor (j );

}

Function floor (){

Return floor (j );

}

VaR pressure = 50000;

VaR A = "";

VaR floor = math. floor;

J = 123.123;

Print ("-------------" nstring conversion test ");

Print ("the empty:", benchmark (empty ));

Print ("Intern:", benchmark (interncast ));

Print ("string :");

Benchmark (stringcast );

Print ("New String :");

Benchmark (newstringcast );

Print ("tostring :");

Benchmark (tostringcast );

Print ("-------------" nfloat to int conversion test ");

Print ("parseint ");

Benchmark (parseint );

Print ("math. Floor ");

Benchmark (mathfloor );

Print ("floor ")

Benchmark (floor );



Function newobject (){

Return new object ();

}



Function internobject (){

Return {};

}

Print ("------------" nliteral test ");

Print ("RunTime new object", benchmark (newobject ));

Print ("literal object", benchmark (internobject ));
Appendix 2

Code 1:

 
For (VAR I = 0; I <100; I ++ ){

Arr [I] = 0;

}

 

Code 2:

 
VaR I = 0;

While (I <100 ){

Arr [I ++] = 0;

}

 

Code 3:

 
VaR I = 0;

While (I <100 ){

Arr [I] = 0;

I ++;

}

 

Test the two pieces of code in Firefox. The result is Code 2 is better than code 1 and 3, while code 1 is generally better than code 3 and sometimes exceeds code 3.
In 6.0, code 2 and 3 are sometimes better than code 1 when the test pressure is high (such as testing more than 10000 times), and sometimes code 1 is far behind, code 2> code 3> code 1 when the test stress is low (for example, 5000 times.

Code 4:

 
VaR I = 0;

VaR;

While (I <100 ){

A = 0;

I ++;

}

 

Code 5:

 
VaR;

For (VAR I = 0; I <100; I ++ ){

A = 0;

}

The test results of the above two pieces of code in Firefox and IE are similar in performance.

Code 6:

 
VaR;

VaR I = 0;

While (I <100 ){

A = I;

I ++;

}

 

Code 7:

 
VaR;

VaR I = 0;

While (I <100 ){

A = I ++;

}

 

Code 8:

VaR;

For (VAR I = 0; I <100; I ++ ){

A = I;

}

 

Code 9:

 
VaR;

For (VAR I = 0; I <100 ;){

A = I ++;

}

The performance of the four pieces of code in Firefox is similar to that in Firefox 6 and 8, and that in Firefox 7 and 9 is similar, while in Firefox 6,
8 <7, 9;

Finally, let's look at the empty loop.

Code 10:

 
For (VAR I = 0; I <100; I ++ ){}

 

Code 11:

 
VaR I;

While (I <100) {I ++ ;}

The last test showed a magical result. The time spent on code 10 in Firefox and the time spent on Code 11 were about. Therefore, it does not have reference value, so I did not show it to you at the beginning.

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.