How to optimize the performance of JavaScript scripts
Author: ShiningRay @ Nirvana Studio
With the development of the network, the speed of online speed and machine is improved, and more and more websites have used enrich client technology. Now Ajax is the most popular way. JavaScript is an interpreted language, so performance cannot reach the level of C / Java, limiting what it can do at the client, in order to improve his performance, I want to have previously made JavaScript for JavaScript. Many tests talk about your own experience, hoping to help you improve your JavaScript scripting performance.
Language level
cycle
The loop is a very common control structure. Most things are done by it. In JavaScript, we can use for (;;), while (), for (in) three cycles, in fact, these three cycles The efficiency of for (in) is extremely efficient because he needs to query the hash key, as long as it can, it should be used less. For (;;) and while cycles, the WHILE cycle is better than for (;;), it may be because of the problem of for (;;) structure, it is necessary to jump back frequently.
Local variables and global variables
The speed of local variables is faster than global variables because the global variable is actually a member of the global object, and local variables are in the stack of functions.
Do not use EVAL
Using EVal is equivalent to the interpretation of the interpretation in the runtime, you need to consume a lot of time. At this time, the closures supported by JavaScript can implement function templates (for the content of the closure, please refer to the content programming)
Reduce object look
Because of JavaScript interpretation, A.b.c.d.e, you need to perform at least 4 query operations, first check A and check B, then check C, so that it is. So if such an expression repeatedly, as long as it is possible, such an expression should be used, and the local variables can be utilized, put it into a temporary place to query.
This can be combined with the cycle because we often loop according to the length of the array, and usually this length is constant, such as each query a.length, you need to make an additional operation, and pre-take VAR Len = a.length, then a query.
String connection
If you are adding a string, it is best to use S = AnotherStr operation, not to use S = S AnotherStr.
If you want to connect multiple strings, you should use it less =, such as
S = a;
S = B;
S = C;
Should be written into S = A B C;
And if you collect strings, for example, you can use a buffer to use a string = operation, it is best to use a cache. How to use it? Use the JavaScript array to collect, and finally connect to the Join method, as follows
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 frequent mistake, because JavaScript is a dynamic type language, you cannot specify the type of variable.
1. Convert the digital to the string, app "" 1, although it looks more ugly, but in fact this efficiency is the highest, performance: ("" )> string ()> .tostring ()> NEW STRING ()
This fact is a bit similar to the following "direct quantity", try to use the internal operations that can be used when you use the user to operate quickly.
String () belongs to the internal function, so the speed is very fast, and .toString () To query the function in the prototype, so the speed is inferior, and new string () is used to return a precise copy.
2. The floating point number is converted into an integer. This is more prone to error. Many people like to use parseint (), in fact, PARSEINT () is used to convert a string into numbers, rather than floating point numbers and integers, we should Use math.floor () or math.Round ().
In addition, the problem in the object lookup in the second section is different, Math is internal object, so Math.Floor () does not have much query method and call time, and the speed is the fastest.
3. For custom objects, if the toString () method is defined for type conversion, it is recommended to explicitly call toString (), because the internal operation is trying to try all the possibilities, try the TOSTRING () method of the object. No transformation into string, so directly call this method efficiency will be higher
Use direct
In fact, this influence is relatively small, it can be ignored. What is the use of direct volume, such as JavaScript supports [param, param, param, ...] to directly express an array, and we have used new array (param, param, ...), using the former directly explaining the engine The latter is to call an Array internal constructor, so it is a little more fast.
Similarly, the way var foo = {} is also better than VAR foo = new object (); fast, varreg = /../; is fast than varreg = new regexp ().
String traversal operation
Looping a string, such as replacement, lookup, should use regular expressions, because the JavaScript is slower, while the regular expression is a language written in C, performance is very good.
Advanced object
Custom advanced objects and DATEs, regexp objects consume a lot of time during construction. If you can be multiplexed, a cache should be used.
DOM related
Insert HTML
Many people like to use Document.Write in JavaScript to generate content to the page. In fact, such efficiency is low. 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 your HTML code into the page.
Object inquiry
Using the [""] query is compared .Items () faster, this is the same as the previous reduction object lookup, call .Items () adds a query and function call.
Create a DOM node
Usually we may use the string to write HTML directly to create a node, actually
Unable to ensure the effective string of the code is low
Therefore, it should be a document.createElement () method, and if there is a ready-made template node in the document, it should be used with a clonEnode () method, because after using the createElement () method, you need to set the properties of multiple elements, using clonenode () Then reduce the number of properties, and if you need to create a lot of elements, you should prepare a template node. Timer
If you are constantly running, you should not use SetTimeout, but you should use SetInterVal. SetTimeout To reset a timer each time.
other
Script engine
According to my testing of Microsoft JScript, it is much worse than Mozilla's Spidermonkey, whether it is executing speed or memory management, because Jscript is basically not updated. But Spidermonkey can't use ActiveXObject
File optimization
File optimization is also a very effective means, deleting all spaces and comments, putting the code in one line, can speed up the speed of the download, pay attention, is the speed of downloading rather than the speed of resolution, if it is local, notes and spaces Will affect interpretation and execution speed.
to sum up
This article summarizes some methods of improving JavaScript running performance in JavaScript programming, in fact, these experiences are based on several principles:
Directly take the hands ready to be fast, such as local variables are fast than global variables, and the direct volume is faster than the runtime. Decrease the number of execution as little as possible, such as first caching needs multiple queries. Use language built-in functions as much as possible, such as string links. Use the API provided by the system as much as possible because these APIs are compiled binary code, and the execution efficiency is high.
At the same time, some basic algorithms can be used in JavaScript, such as the adjustment of the computational structure, here is not described again. However, since JavaScript is interpreted, it is generally not optimized at runtime, so these optimization is still very important.
Of course, in fact, some of the techniques here are also used in some other interpreted languages, and everyone can use.
reference
Http://www.umsu.de/jsperf/ Test comparison of various browsers http://home.earthLink.NET/~kendrasg/info/js_opt/
appendix
Because it is the test before, the test code is not complete, I added a part as follows:
VAR Print;
IF (TypeOf Document! = "undefined") {
Print = Document.write;
} 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 f (i ); } Var end = (new date ()). getTime (); Wscript.echo (end-start); } / * i = 0 START = (new date ()). gettime (); While (i <60000) { C = [I, I, I, I, I, I, I, 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, 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.toTOString (); } Function parse () { 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 ("---------- / nlitral test"); Print ("Runtime New Object", Benchmark (NewObject)); Print ("Literal Object", Benchmark (InternObject));