Home > Web Front-end > JS Tutorial > JS performance optimization notes search and organization_javascript skills

JS performance optimization notes search and organization_javascript skills

WBOY
Release: 2016-05-16 17:24:53
Original
1165 people have browsed it

Learn about performance optimization by searching for information online. We have summarized it briefly for your reference only during the optimization process. If you have any questions, please ask them in time and make corresponding additional modifications.

1. Keep the code concise: some simple expressions will also produce good optimizations

eg: x=x 1; it can be abbreviated to x without affecting the function;

2. Keep variable names and method names as simple as possible without affecting the semantics. (You can choose to name it with the first letter)

eg: The length of the defined array can be named: ArrLen instead of ArrayLength.

3. Regarding JS loops, loops are a commonly used process control.

JS provides three types of loops: for(;;), while(), and for(in). Among these three types of loops, for(in) is the least efficient because it needs to query the Hash key. Therefore, the for(in) loop should be used as little as possible. The performance of for(;;) and while() loops is basically the same. Of course, it is recommended to use a for loop. If the loop variable is incrementing or decrementing, do not assign a value to the loop variable alone. Instead, use the nested or – operator.

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

Because we often need to loop based on the length of strings and arrays, and usually this length is unchanged. For example, every time we query a.length, we need to perform an additional operation and put var len= in advance. a.length, then there is one less query.

5. Try to use local variables instead of global variables.

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

6. Use eval as little as possible.

Every time you use eval, it takes a lot of time. At this time, you can use the closure supported by JS to implement function templates.

7. Reduce object search

Because of the interpretability of JavaScript, a.b.c.d.e requires at least 4 query operations. First check a, then check b in a, and then check c in b. , and so on. Therefore, if such expressions appear repeatedly, such expressions should be kept as rare as possible as much as possible. You can use local variables to put them in a temporary place for querying.

8. String concatenation.

If you are appending a string, it is best to use the s =anotherStr operation 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; it should be written as s =a b c;
If you want to collect strings, such as multiple If you perform the = operation on the same string several times, it is best to use a cache. How to use it? Use JavaScript arrays to collect, and finally use the join method to connect, as follows

Copy code The code is as follows:

var buf = new Array();for(var i = 0; i < 100; i ){ buf.push(i.toString());}var all = buf.join("");

9. Type conversion

1. Convert numbers into strings, using "" 1. Although it looks a bit uglier, in fact this is the most efficient, in terms of performance: ("" ) > String() > .toString() > new String()

Try to use internal operations that can be used at compile time to be faster than user operations used at runtime.

String() is an internal function, so it is very fast, while .toString() needs to query the function in the prototype, so it is not as fast. new String() is used to return an exact copy.

2. Converting floating point numbers to integers is more error-prone. Many people like to use parseInt(). In fact, parseInt() is used to convert strings into numbers, not between floating point numbers and integers. To convert between, we should use Math.floor() or Math.round(). Math is an internal object, so Math.floor() actually does not take much querying method and calling time, and 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 will try the object after trying all possibilities. The toString() method tries to see if it can be converted into String, so calling this method directly will be more efficient

10. Try to use JSON format to create objects instead of the var obj=new Object() method.

Because the former is copied directly, while the latter needs to call the constructor, the performance of the former is better.

11. When you need to use an array, try to use the syntax of JSON format.

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

12. Use regular expressions to perform loop operations on strings, such as replacement and search.

Because the loop speed of JS is relatively slow, and the regular expression operation is an API written in C, which has better performance.

13. Insert HTML

Many people like to use document.write in JavaScript to generate content for the 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 your own HTML code into the page.

14. Object query

Using [""] query is faster than .items()

15. Timer

If for The code is constantly running. SetTimeout should not be used, but setInterval should be used. setTimeout resets a timer each time.

16. Minimize DOM calls

In web development, a very important role of JavaScript is to operate the DOM. However, operating on the DOM is very expensive because it causes the browser to perform a reflow operation. We should reduce DOM operations as much as possible.
Reflow operations mainly occur in several situations:
* Change the size of the form
* Change the font
* Add and remove stylesheet blocks
* Change the content even if it is input text in the input box
* CSS virtual classes are triggered such as: hover
* Change the className of the element
* When adding or deleting operations or content changes are performed on DOM nodes.
* 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 reflows caused by DOM operations:
1. Before operating on the current DOM, do as much preparation work as possible to ensure N times of creation and 1 time of writing.
2. Before operating on the DOM, delete the element to be operated from the current DOM structure:
2.1. Realize deletion through removeChild() or replaceChild().
2.2. Set the display style of this element to "none".

3.CSS part
Another situation that often causes reflow operations is to modify the appearance of an element through the style attribute, such as element.style.backgroundColor = "blue";
Each time the element is modified The style attribute will definitely trigger the reflow operation. To solve this problem, you can:
3.1. Use the method of changing className to replace style.xxx=xxx.
3.2. Use style.cssText = ''; to write the style once.
3.3. Avoid setting too many inline styles
3.4. Try to set their positions as fixed or absolute for added extra-structural elements
3.5. Avoid using tables for layout
3.6. Avoid using CSS Use JavaScript expressions (IE only)
4. Cache the obtained DOM data. This method is particularly important for obtaining properties that will trigger reflow operations (such as offsetWidth, etc.).
5. When operating on the HTMLCollection object, the number of accesses should be minimized as much as possible. At its simplest, you can cache the length attribute in a local variable, which can greatly improve the efficiency of the loop. efficiency.

17. Refactor <script> and <style> calling methods or merge js files to optimize the number of requests, and try to use external links to reference <br><br>We often use an HTML file You see this code in the header: <br><br><script src="/scripts/a.js"></script>





In most cases, the above code can is simplified to:



where a.js/b.js is referenced in d.js /c.js. Written via the document.write method.

18. For large JS objects, since the creation time and space overhead are relatively large, caching should be considered as much as possible.

19. Place the script at the bottom.

Scripts are generally used for user interaction. It is recommended to wait until the page is loaded before loading the js file. So, scripts are just the opposite of CSS, scripts should be placed at the bottom of the page.

20. Remove blank areas in JavaScript

You can use relevant tools to remove blank comments, etc. Renaming all names with one or two letters will bring significant improvements . (But you need to keep an unaccepted backup file to facilitate future maintenance)
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template