Web tutorials: How to optimize the performance of JavaScript scripts

Source: Internet
Author: User
Tags empty eval execution expression final connect variables javascript array
javascript| Script | tutorials | Web page | performance | optimization

Author: shiningray @ Nirvana Studio

With the development of the network and the speed of the machine, more and more websites use the rich client technology. Now Ajax is one of the most popular ways. JavaScript is an interpreted language, so it can't reach the level of C/java and so on, limiting what it can do on the client, and in order to improve his performance, I want to talk about my experience based on a lot of the tests I've done on JavaScript before. Hopefully it will help you improve your JavaScript scripting performance.

Language level aspects
Cycle
Loops are a very common control structure, most things depend on it to do it, in JavaScript we can use for (;;), while (), for (in) three loops, in fact, in these three loops for (in) is very inefficient because he needs to query the hash key, As long as you can, you should try to use less. for (;;) The performance of the while loop should be the same as the basic (usually used) equivalent.

In fact, the use of these two cycles, there is a great stress. I have some interesting situations in the test, see appendix. The final conclusion is:

If the loop variable is incremented or decremented, do not assign a value to the loop variable alone, and you should use the nested + + or-operator when it last reads.

If you want to compare the length of an array, you should put the length property of the array into a local variable in advance, reducing the number of queries.

Local variables 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 stack of functions.

Do not use eval
Using Eval is equivalent to invoking the interpretation engine to run the content at run time, which takes a lot of time. This time using JavaScript-supported closures enables functional templates (refer to functional programming for the contents of closures)

Reduce Object Lookup
Because of the interpretation of JavaScript, so a.b.c.d.e, you need to do at least 4 query operations, first check A and then check a B, and then check C in B, so down. So if this expression repeats itself, as long as possible, you should try to minimize the expression, you can use the local variable, put it into a temporary place to query.

This can be combined with the loop, because we often have to cycle according to the length of the string, the array, and usually this length is constant, such as every query a.length, you need to do an extra operation, and the Len=a.length Var, then a query less.

string concatenation
If you are appending a string, it is best to use the S+=ANOTHERSTR action instead of using S=S+ANOTHERSTR.

If you want to connect multiple strings, you should use + = less, such as

S+=a;s+=b;s+=c;
should be written

S+=a + B + C;
If you are collecting strings, such as + + for the same string multiple times, it is best to use a cache. How to use it? Use a JavaScript array to collect, and then connect using the Join method, as follows

var buf = new Array (); for (var i = 0; i < i++) {Buf.push (i.tostring ());} var all = Buf.join ("");
Type conversions
Type conversions are common mistakes, because JavaScript is a dynamic type language and you can't specify the type of variable.

1. Convert numbers to strings, apply "+ 1", although it looks ugly, but in fact this efficiency is the highest, performance up to say:

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

This is actually a bit like the "direct volume" below, where you can use an internal operation that you use at compile time faster than the user operation used at run time.

A string () is an intrinsic function, so it is very fast, and. ToString () to query the function in the prototype, so the speed is somewhat inferior, and the new String () is used to return an exact copy.

2. Floating point conversion to integer type, this is more error-prone, many people like to use parseint (), in fact, parseint () is used to convert strings to numbers, rather than floating-point number and integer conversion between, we should use Math.floor () or Math.Round ().

In addition, unlike the problem in the second section of the object lookup, math is an internal object, so Math.floor () actually does not have much of a query method and the time to call, the fastest speed.

3. For custom objects, if the ToString () method is defined for type conversion, an explicit call to ToString () is recommended, because an internal operation attempts to convert the object's ToString () method to a string after attempting all possibilities. So it would be much more efficient to call this method directly.

Use Direct quantity
In fact, this effect is relatively small, can be ignored. What is called using the direct amount, for example, JavaScript supports using [Param,param,param,...] To express an array directly, we used to use the new array (Param,param,...), which is explained directly by the engine, which calls an array internal constructor, so a little bit faster.

Similarly, var foo = {} is also way more than var foo = new Object (), fast, var reg =/. /; faster than Var reg=new RegExp ().

String traversal operation
Looping strings, such as substitution and lookup, should use regular expressions, because JavaScript itself is slow to circulate, and regular expressions operate as APIs for languages written in C, and perform well.

Advanced objects
Custom advanced objects and date, RegExp objects can consume a lot of time when they are constructed. If you can reuse, you should use the caching method.

Dom related
Inserting HTML
Many people like to use document.write in JavaScript to generate content for a 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 their innerhtml to insert their own HTML code into the page.

Object Query
Using the ["] query is faster than. Items (), which is similar to the previous idea of reducing object lookup, and calling. Items () Adds a single call to the query and function.

Creating a DOM node
Normally we might use strings to write HTML directly to create nodes, actually doing

Cannot guarantee the validity of the code

Low string operation efficiency

So you should use the Document.createelement () method, and if there are ready-made boilerplate nodes in the document, you should use the CloneNode () method, because after you use the createelement () method, you need to set the attributes of multiple elements. With CloneNode () you can reduce the number of times a property is set--and if you need to create many elements, you should prepare a boilerplate node first.

Timer
If you are working with code that is running, you should not use settimeout instead of setinterval. SetTimeout each time you want to reset a timer.

Other
Script engine
My test of Microsoft's JScript is much worse than Mozilla's SpiderMonkey, whether it's execution speed or memory management, because JScript is now basically not updated. But SpiderMonkey can't use ActiveXObject

File optimization
File optimization is also a very effective means to delete all the blanks and comments, put the code in a row, you can speed up the download speed, note that the speed of the download rather than the speed of resolution, if it is local, comments and spaces do not affect the interpretation and execution speed.

Summarize
This article summarizes some of the ways that I've found in JavaScript programming to improve the performance of JavaScript, but these experiences are based on several principles:

It's quicker to take things that are readily available, such as local variables that are faster than global variables, and the direct amount is faster than the Run-time construction object, and so on.

Reduce the number of executions as little as possible, such as caching requires multiple queries.

Use language-built-in features, such as String links, whenever possible.

Use the API provided by the system whenever possible, because these APIs are compiled binary code that is highly efficient

At the same time, some basic algorithms for optimization, also can be used in JavaScript, such as the adjustment of the structure of the operation, here is no longer repeat. However, since JavaScript is interpreted and generally does not optimize bytecode at run time, these optimizations are still important.

Of course, some of the techniques here are also used in other interpretive languages and can be referenced.

Reference
http://www.umsu.de/jsperf/test comparisons for various browsers

http://home.earthlink.net/~kendrasg/info/js_opt/

Appendix 1
Since the test code is incomplete because it was a previous test, I have added some of the following:

var print;if (typeof document!= "undefined") {    print = function () {  document.write (arguments[0)) ; }}else if (typeof WScript!= "undefined") {    print = function () {      & nbsp 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=0start = (new Date ()). GetTime () while (I < 60000) {    C = [i,i,i,i,i,i,i,i,i,i];     i++;} End = (new Date ()). GetTime (); WScript.Echo (End-start); I=0start = (new Date ()). GetTime (); while (I < 60000) {    C = new Array (I,i,i,i, i,i,i,i,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");p R Int ("The Empty:", Benchmark (empty));p rint ("Intern:", Benchmark (interncast));p rint ("String:"); Benchmark (stringcast );p rint ("New String:"), Benchmark (newstringcast);p rint ("toString:"), Benchmark (tostringcast);p rint ("------------- \nfloat to Int conversion Test ");p rint (" parseint "); Benchmark (parseint);p rint (" Math.floor "); benchmark (Mathfloor); Print ("Floor") benchmark (floor); function NewObject () {    return new Object ();} FunctIon Internobject () {    return {};} Print ("------------\nliteral Test");p rint ("Runtime New Object", Benchmark (newobject));p rint ("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 <) {arr[i++]=0; }

Code 3:

var i = 0;        while (I <) {arr[i]=0;    i++; }

Test these two pieces of code under Firefox, the result is that code 2 is better than code 1 and 3, and code 1 is generally better than code 3, sometimes more than code 3, and in IE 6.0, code 10,000 and 2, such as testing more than 3 times, are sometimes better than code 1. Sometimes it's far behind code 1, and when the test pressure is small (like 5,000 times), the Code 2> code 3> code 1.

Code 4:

var i = 0;    var A;        while (I <) {a = 0;    i++; }

Code 5:

var A;    for (Var i=0;i<100;i++) {a = 0; }
The above two pieces of code in Firefox and IE under the test results are close performance.

Code 6:

var A;    var i=0;        while (i<100) {a=i;    i++; }

Code 7:

var A;    var i=0;    while (i<100) {a=i++; }

Code 8:

var A;    for (Var i=0;i<100;i++) {a = i; }

Code 9:

var A;    for (Var i=0;i<100;) {a = i++; }
These four snippets of code in Firefox under 6 and 8 performance close, 7 and 9 performance close, while 6, 8 < 7, 9;

Finally, let's take a look at the empty loop

Code 10:

for (Var i=0;i<100;i++) {}

Code 11:

var i;    while (i<100) {i++; }
The final test showed a magical result, and the time that Firefox spent on code 10 and code 11 spent is about 24:1. So it doesn't have a reference value, so I didn't put it in the first place for everyone to see.



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.