Javascript performance optimization Summary

Source: Internet
Author: User

Loop

Loop is a commonly used control structure. Most things are completed by it. In JavaScript, we can use for (;), while (), for (in) in fact, the efficiency of for (in) in these three loops is very poor, because it needs to query hash keys, as long as it can be used as little as possible. The performance of for (;) and while loops is equivalent to that of normally used loops.

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 -- operators during the last read.

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

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

Using Eval 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

A. b. c. d. e. You must perform at least four query operations. Check a first, then B in A, and then C in B. 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 query. length, an additional operation is required, and the VaR

Len = A. length, a query is missing.

String connection

If it is an append string, it is best to use the S + = anotherstr operation instead of the S = S + anotherstr operation.

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

S + = A; 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.

To convert a number into a string, apply "" + 1. Although it looks ugly, the efficiency is actually the highest. In terms of 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 () is used to query functions in the prototype, so the speed is inferior. New String () is used to return an exact copy.

2.

Converting a floating point to an integer is more prone to errors. Many people prefer parseint (). In fact, parseint () is used to convert a string to a number, rather than converting between a floating point and an integer, we should use math. floor () or math. round ().

In addition, math is an internal object, which is different from the problem in Object Search in section 2. Therefore, math. Floor () does not actually have many query methods and call times, and the speed is the fastest.

3.

For custom objects, if the tostring () method is defined for type conversion, we recommend that you explicitly call tostring (), because after all the possibilities of internal operations are attempted, will try to convert the tostring () method of the object to string, so it is more efficient to directly call this method.

Direct usage

In fact, this effect is relatively small and can be ignored. For example, JavaScript supports the use of [Param,...] in the past, we used new array (Param, Param ,...), the former is directly explained by the engine, and the latter calls an array internal constructor, so it is a little faster.

Similarly, VAR Foo = {} is faster than VaR Foo = new object (); and VAR Reg =/.../; is faster than VaR Reg = new Regexp.

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 objects and date and Regexp objects consume a lot of time during construction. If reusable, cache should be used.

Dom-related

Insert HTML

Many users prefer to use document. Write in JavaScript to generate content for pages. 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 innerhtmlCodeInsert to the page.

Object Query

Use [""] to query. items () is faster, which is the same as the previous idea of reducing object search. items () adds a query and function call.

Create a DOM Node

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

Code validity cannot be guaranteed

Low string operation efficiency

So we should use document. createelement () method. If there is a ready-made template node in the document, you should use the clonenode () method. Because after using the createelement () method, you need to set attributes of multiple elements, using clonenode () can reduce the number of attribute settings-if you need to create many elements, you should first prepare a template node.

Timer

If you are targeting constantly running code, you should not use setTimeout, but setinterval. SetTimeout you need to reset a timer each time.

Others

Script Engine

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. However, spidermonkey cannot use 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:

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.

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

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

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.

From: http://developer.51cto.com/art/200906/128404.htm

 

 

Supplement:

1. uniformly place public JS files on the file server or Google hosting

2. Compress JS files

Manual compression: here we recommend a good site, http://www.css88.com/tool/ysjs/

Automatic compression: vs2008 has an automatic compression plug-in, which is said to be automatically compressed into a file with the same name, such as myjs. the JS file will be compressed into myjs. min. JS, we only need to reference myjs. min. JS files.

3. Add/* @ cc_on Doc = Document; EVAL ('document = doc') to the first line of the Code in the JS file ');@*/

However, this method does not work if the code is small. Here is a test example: // before

VaR Date =   New Date;
For ( VaR I =   0 ; I <   100000 ; I ++ ) Document;
Alert ( New Date - Date ); // 643

/* @ Cc_on _ d = Document; EVAL ('var document = _ D ')@ */

// After
Date =   New Date;
For ( VaR I =   0 ; I <   100000 ; I ++ ) Document;
Alert ( New Date - Date ); // 145

 

You can also refer to the more detailed explanation: http://www.cnblogs.com/xiaopin/archive/2010/12/01/1892692.html

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.