JS performance optimization notes search and sorting

Source: Internet
Author: User

Find information on the Internet to learn about performance optimization. The content is now easy to organize and can be used only for your reference during the optimization process. If you have any questions, please submit them in time, then make relevant supplementary changes.

1. Make the code concise: some simple expressions will also produce good Optimization

E. g: x = x + 1; it can be abbreviated as x ++ without affecting the function;

2. The variable name method should be as simple as possible without affecting the semantics. (You can select the initial name)

For example, to define the length of an array, you can name it ArrLen instead of ArrayLength.

3. About JS loops, loop is a common process control.

JS provides three types of loops: for (;), while (), and for (in ). In these three loops, the efficiency of for (in) is the worst, because it needs to query the Hash key, so we should try to use less for (in) loops, for (;), while () the cyclic performance is basically the same. Of course, we recommend that you use a for loop. If the variable increments or decreases, do not assign values to the variable separately. Instead, use nested ++ or-operators.

4. If you need to traverse the array, you should first cache the array length and put the array length into a local variable to avoid multiple query of the array length.

Because we often need to cycle according to the length of the string and array, 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.

5. Use local variables instead of global variables as much as possible.

The access speed of local variables is faster than that of global variables, because global variables are actually members of the window object, and local variables are placed in the function stack.

6. Use eval as few as possible.

It takes a lot of time to use eval each time. In this case, the closure supported by JS can be used to implement function templates.

7. 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.

8. String connection.

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

If you want to connect multiple strings, use less + =, for example, s + = a; s + = B; s + = c; write 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:
Copy codeThe Code is as follows:
Var buf = new Array (); for (var I = 0; I <100; I ++) {buf. push (I. toString ();} var all = buf. join ("");

IX. type conversion

1. convert a 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 ()

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 (). Math is an internal object, So Math. floor () does not actually have much query methods and call time, 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.

10. Try to create an Object in JSON format instead of var obj = new Object.

Because the former is a direct copy, while the latter needs to call the constructor, the former has better performance.

11. When arrays are required, try to use the JSON format syntax,

You can use the following syntax to define an array: [parrm, param, param...], instead of using new Array (parrm, param, param ...) this syntax. Because the syntax in JSON format is directly interpreted by the engine. The latter requires calling the Array constructor.

12. Use a regular expression to perform cyclic operations on strings, such as replacement and search.

The speed of JS loops is slow, while the regular expression operation is an API written in C, which has better performance.

13. 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.

14. Object Query

Query with [""] is faster than. items ()

15. Timer

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

Sixteen. Minimize DOM calls

In Web development, a very important role of JavaScript is to operate the DOM. However, DOM operations are very expensive, because this will cause the browser to execute the reflow operation. We should try to reduce DOM operations as much as possible.
Reflux operations may occur in the following situations:
* Change the form size.
* Changing the font
* Add and remove stylesheet Blocks
* The content is changed, even if it is input text in the input box.
* The CSS virtual class is triggered, for example, hover.
* Change the className of an element.
* When a DOM node is added or deleted or its content is changed.
* When setting a style dynamically (such as element. style. width = "10px ").
* When obtaining a size value that must be calculated, such as accessing offsetWidth, clientHeight, or other CSS values that need to be calculated
The key to solving the problem is to limit the number of backflows caused by DOM operations:
1. Make as many preparations as possible before performing operations on the current DOM to ensure N creation and 1 Write.
2. Before DOM operations, delete the elements to be operated from the current DOM structure:
2.1. Delete objects in the true sense through removeChild () or replaceChild.
2.2. Set the display style of the element to "none ".

3. CSS Section
Another common cause of backflow is to modify the appearance of an element through the style attribute, such as element. style. backgroundColor = "blue ";
Each time you modify the style attribute of an element, the reflux operation will be triggered. To solve this problem, you can:
3. 1. Replace style. xxx = xxx with the className method.
3.2.use style.css Text = ''; write the style at one time.
3.3. Avoid setting too many in-row styles
3.4. Try to set the positions of the elements outside the structure to fixed or absolute.
3.5. Avoid table layout
3.6. Avoid using JavaScript expressions (IE only) in CSS)
4. cache the retrieved DOM data. This method is especially important for obtaining attributes that will trigger backflow operations (such as offsetWidth.
5. when you operate an HTMLCollection object, you should minimize the number of accesses as much as possible. You can cache the length attribute in a local variable, in this way, the cycle efficiency can be greatly improved.

17. refactor the <script> and <style> call methods or merge js files to optimize the number of requests, and try to use external links for reference.

We often see the following code in an HTML file header:

<Script src = "/scripts/a. js"> </script>

<Script src = "/scripts/B. js"> </script>

<Script src = "/scripts/c. js"> </script>

In most cases, the above Code can be simplified:

<Script src = "/scripts/d. js"> </script>

Among them, d. js references a. js/B. js/c. js. Write data using the document. write method.

18. For large JS objects, the cache should be considered as much as possible because the Creation Time and Space overhead are large.

19. Put the script at the bottom.

Scripts are generally used for user interaction. We recommend that you load the js file after the page is loaded. Therefore, the script and CSS are the opposite. The script should be placed at the bottom of the page.

20. Remove the blank area in JavaScript

You can use related tools to remove blank comments. renaming all names with one or two letters will significantly improve. (However, an unaccepted backup file is required for future maintenance)

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.