JavaScript Scripting Performance Tuning considerations _javascript Tips

Source: Internet
Author: User
Tags eval javascript array
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 do you 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 is 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.
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.