JavaScript script performance optimization considerations

Source: Internet
Author: User

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.
  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 var len =. length, then one 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. Convert the number into a string and 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 innerHTML to insert their HTML code into 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 basic algorithm optimizations can also be used in JavaScript. For example, the adjustment of the computing structure will not be repeated here. 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.

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.