I read it published by the blog site.Article30 good experiences on improving the execution efficiency of web programs. These 30 guidelines are very useful for web development, however, you may know some of these principles, but do not know why.
The following is my understanding and analysis of these Principles. Some JS performance standards have also been tested. You can download the demo page. If your understanding is incorrect, please correct me. You are also very welcome to add this article.
Test environment:
OS: Vista;
Processor: 3.40 GHz;
Memory: 2.00 GB;
System type: 32-bit operating system;
Browser: IE8, forefox 3.5.7, chrome4.0.249
1. Avoid using dom as much as possible. When Dom needs to be used repeatedly, the reference to Dom should be saved to the local JavaScript variable before use. Use the innerhtml setting method to replace document. createelement/appendchild.
We can use the followingCodeTest:
Function testinnerhtml () {var div1 = document. getelementbyid ("testdiv"); var starttime = new date (); var Buf = new array (); For (VAR n = 0; n <5000; n ++) {Buf. push ('<a href = ""> test'); Buf. push (n); Buf. push ('</a>');} div1.innerhtml = Buf. join (''); document. getelementbyid ('vshowtime1 '). innerhtml = 'time consumed 1: '+ (new date ()-starttime) + 'ms'; div1.innerhtml = "";} function testcreateelement () {var div1 = document. getelementbyid ("testdiv"); var starttime = new date (); For (VAR n = 0; n <5000; n ++) {var E = document. createelement ('A'); E. href = ''; E. innertext = 'test' + N; div1.appendchild (E);} document. getelementbyid ('divshowtime2 '). innerhtml = 'time consumed 2: '+ (new date ()-starttime) + 'ms'; div1.innerhtml = "";}
Test results:
|
IE8 |
Firefox |
Chrome |
1 |
Time consumed: 1 ms, 134 Ms Time consumed: 857 Ms |
Time consumed: 1 ms, 570 Ms Time consumed: 658 Ms |
Time consumed: 61 Ms Time consumed: 47 Ms |
2 |
Time consumed: 1 ms, 131 Ms Time consumed: 846 Ms |
Time consumed: 1 ms, 474 Ms Time consumed: 610 Ms |
Time consumed: 58 Ms Time consumed: 48 Ms |
3 |
Time consumed: 1 ms, 131 Ms Time consumed: 927 Ms |
Time consumed: 1 ms, 673 Ms Time consumed: 674 Ms |
Time consumed: 57 Ms Time consumed: 2: 49 Ms |
4 |
Time consumed: 1 ms, 132 Ms Time consumed: 846 Ms |
Time consumed: 1 ms, 540 Ms Time consumed: 686 Ms |
Time consumed: 55 ms Time consumed: 46 Ms |
The test results show that innerhtml is used to compare the document. createelement/appendchild () method. In IE8, the efficiency is improved significantly, but there is little difference between Firefox and chrome.
2. There is a problem with eval (). The new fuction () constructor is also. Try to avoid using them.
The eval method has one more step of parsing than the direct call method, so try to avoid using it. If you must use it, it is best to wrap the called code into the function, and then the eval function, this reduces the parsing time. For eval function efficiency, we can use the following code to test:
Function testnoeval () {var starttime = new date (); For (VAR I = 0; I <500000; I ++) {var STR = 'test ';} vaR endtime = new date (); document. getelementbyid ('vshowtime1 '). innerhtml = 'time consumed 1: '+ (endtime-starttime) + 'ms';} function testeval () {var starttime = new date (); eval ("For (VAR I = 0; I <500000; I ++) {var STR = 'test';}"); var endtime = new date (); document. getelementbyid ('divshowtime2 '). innerhtml = 'time consumed 2: '+ (endtime-starttime) + 'ms ';}
Test results:
|
IE8 |
Firefox |
Chrome |
1 |
Time consumed: 85 Ms Time consumed: 251 Ms |
1: 2 ms Time consumed: 203 Ms |
Time consumed: 1 ms Time consumed: 340 Ms |
2 |
Time consumed: 82 Ms Time consumed: 251 Ms |
1: 2 ms Time consumed: 204 Ms |
1: 2 ms Time consumed: 344 Ms |
3 |
Time consumed: 81 Ms Time consumed: 250 ms |
1: 2 ms Time consumed: 205 Ms |
Time consumed: 1 ms Time consumed: 338 Ms |
4 |
Time consumed: 82 Ms Time consumed: 251 Ms |
1: 2 ms Time consumed: 213 Ms |
1: 2 ms Time consumed: 344 Ms |
Tests show that the eval efficiency is much slower, especially in Firefox and chrome. The execution principle of new function is similar to that of Eval, so the efficiency is not high.
3. The with statement is denied. It causes you to search for such a namespace When referencing this variable. The code in with is completely unknown during compilation.
The reason is clear, but the with statement is very concise, and I often use this statement.
4. Use the for () loop instead of... In cycle. Because... Before the in loop starts, the script engine needs to create a list containing all the cyclic attributes and check the list once more.
The reason is clear and not supplemented.
5. Place the try-catch statement outside the loop. Do not place it in the loop because exceptions rarely occur. Avoid executing them every time.
The reason is clear. This is what I think is necessary to use any language.
6. I have even mentioned this in the Bible-not global. The lifecycle of a global variable runs through the lifecycle of the script, and the existence range of the local variable disappears with the destruction of the local namespace. When a global variable is referenced in a function or elsewhere, the script engine needs to search for the entire global namespace.
Prevent memory leaks and increase the search and resolution speed. In addition, variables are defined within the minimum scope of use, and the code is readable.
7. fullname + = 'john'; fullname + = 'holdings '; the execution speed is faster than fullname + = 'john' + 'holdings ';
Use the test code:
Function teststring1 () {var starttime = new date (); For (VAR I = 0; I <500000; I ++) {var fullname = ""; fullname + = 'john'; fullname + = 'holdings ';} var endtime = new date (); document. getelementbyid ('vshowtime1 '). innerhtml = 'time consumed 1: '+ (endtime-starttime) + 'ms';} function teststring2 () {var starttime = new date (); For (VAR I = 0; I <500000; I ++) {var fullname = ""; fullname + = 'john' + 'holdings ';} var endtime = new date (); document. getelementbyid ('divshowtime2 '). innerhtml = 'time consumed 2: '+ (endtime-starttime) + 'ms ';}
Test results:
|
IE8 |
Firefox |
Chrome |
1 |
Time consumed: 1 ms, 492 Ms Time consumed: 477 Ms |
Time consumed: 1 ms, 151 Ms Time consumed: 7 ms |
Time consumed: 52 Ms Time consumed: 1 ms |
2 |
Time consumed: 1 ms, 532 Ms Time consumed: 456 Ms |
Time consumed: 1 ms, 150 ms Time consumed: 7 ms |
Time consumed: 50 ms Time consumed: 1 ms |
3 |
Time consumed: 1 ms, 493 Ms Time consumed: 454 Ms |
Time consumed: 1 ms, 148 Ms Time consumed: 7 ms |
Time consumed: 53 Ms Time consumed: 50 ms |
4 |
Time consumed: 1 ms, 491 Ms Time consumed: 466 Ms |
Time consumed: 1 ms, 204 Ms Time consumed: 8 ms |
Time consumed: 51 Ms Time consumed: 50 ms |
The test results are unexpected. In IE8 and chrome, the efficiency is similar, but in Firefox, the first writing method is much slower than the second one. The same is true for tests in IE6. It seems that this rule remains to be further studied.
8. If you need to connect multiple strings, it is best to make them into an array and then call the join () method to perform this operation. This method is particularly effective when generating HTML fragments.
Verify whether to use the test code:
Function testnojoin () {var starttime = new date (); var teststr = "abcdefghqwertyuiolkjmzxv"; var result = ""; for (VAR I = 0; I <50000; I ++) Result + = teststr; document. getelementbyid ('vshowtime1 '). innerhtml = 'time consumed 1: '+ (new date ()-starttime) + 'ms';} function testjoin () {var starttime = new date (); vaR teststr = "abcdefghqwertyuiolkjmzxv"; var result = ""; var STRs = new array (); For (VAR I = 0; I <50000; I ++) STRs [I] = teststr; Result = STRs. join (""); document. getelementbyid ('divshowtime2 '). innerhtml = 'time consumed 2: '+ (new date ()-starttime) + 'ms'; STRs = NULL ;}
Test results:
|
IE8 |
Firefox |
Chrome |
1 |
Time consumed: 19 ms Time consumed: 2: 25 ms |
1: 25 ms Time consumed: 2: 25 ms |
Time consumed: 15 ms Time consumed: 9 ms |
2 |
Time consumed: 28 Ms Time consumed: 2: 25 ms |
Time consumed: 24 Ms Time consumed: 2: 25 ms |
Time consumed: 16 Ms Time consumed: 8 ms |
3 |
Time consumed: 17 ms Time consumed: 2: 25 ms |
1: 25 ms Time consumed: 2: 25 ms |
Time consumed: 4 ms Time consumed: 8 ms |
4 |
Time consumed: 16 Ms Time consumed: 2: 25 ms |
Time consumed: 28 Ms Time consumed: 27 Ms |
Time consumed: 4 ms Time consumption: 2: 11 ms |
We can see that this rule is not efficient in mainstream browsers. In IE6 testing, the first method is indeed much less efficient than the second method, so this rule is outdated.
9. For simple tasks, it is best to use basic operations instead of function calls. For example, val1 <val2? Val1: val2; execution speed faster than math. Min (val1, val2);, similarly, myarr. Push (newele); slower than myarr [myarr. Length] = newele;
This article is easy to understand and the original ecology is good.
10. Passing a function reference as a parameter to setTimeout () and setinterval () is better than passing a function name as a string parameter (hard encoding ). For example, setTimeout ("somefunc ()", 1000) is less efficient than setTimeout (somefunc, 1000)
The principle is similar to the above eval method.
11. Avoid Dom operations when performing traversal. The Dom element queue obtained through the getelementsbytagname () method is dynamic. It may have been changed before you traverse it. This may lead to an endless loop.
Not supplemented.
12. When you perform repeated operations on Object members (attributes or methods), you must first store references to them. For example, VAR gettags = Document. getelementsbytagname; gettags ('div ');
In my opinion, the example of this rule does not express the meaning of the rule, so it is not a good example. And I tested it according to its example, and did not find the difference between the two, so I re-write the test code as follows:
Function testmethod1 () {var starttime = new date (); var tag = document. getelementbyid ('testdiv '); For (VAR I = 0; I <50000; I ++) var color = tag. style. backgroundcolor; document. getelementbyid ('vshowtime1 '). innerhtml = 'time consumed 1: '+ (new date ()-starttime) + 'ms';} function testmethod2 () {var starttime = new date (); for (VAR I = 0; I <50000; I ++) var color = document. getelementbyid ('testdiv '). style. backgroundcolor; document. getelementbyid ('divshowtime2 '). innerhtml = 'time consumed 2: '+ (new date ()-starttime) + 'ms ';}
Test results:
|
IE8 |
Firefox |
Chrome |
1 |
Time consumed: 1 ms, 400 ms Time consumed: 1071 Ms |
Time consumed: 1 ms, 115 ms Time consumed: 303 Ms |
Time consumed: 28 Ms Time consumed: 2: 63 MS |
2 |
Time consumed: 1 ms, 404 Ms Time consumed: 1081 Ms |
Time consumed: 1 ms, 116 Ms Time consumed: 298 Ms |
Time consumed: 27 Ms Time consumed: 2: 63 MS |
3 |
Time consumed: 17 ms Time consumed: 2: 25 ms |
Time consumed: 1 ms, 115 ms Time consumed: 287 Ms |
Time consumed: 27 Ms Time consumed: 62 Ms |
4 |
Time consumed: 1 ms, 399 Ms Time consumed: 1080 Ms |
Time consumed: 1 ms, 119 Ms Time consumed: 280 Ms |
Time consumed: 29 Ms Time consumed: 62 Ms |
This result is also easy to understand. After all, the DOM function is called one more time!
13. In any code segment, a local variable reference is stored outside the scope of the local variable. For example
Function Foo (ARR ){
VaR A = 'something ';
// Variable 'A' is an out-of-range variable for the following section. The reference of this variable is useful in many cases.
For (VAR I = 0, j = A, looplen = arr. length; I <looplen; I ++ ){
// Do something
}
}
I did not understand the main meaning of this section.
14. For (VAR I = 0; I <somearray. length; I ++ ){...} The execution efficiency is lower than for (VAR I = 0, looplen = somearray. length; I <looplen; I ++ ){...}.
Example:
Function testloop1 () {var somearray = new array (); For (VAR I = 0; I <50000; I ++) {somearray. push (I) ;}var starttime = new date (); For (VAR J = 0; j <somearray. length; j ++) VaR value = somearray [J]; document. getelementbyid ('vshowtime1 '). innerhtml = 'time consumed 1: '+ (new date ()-starttime) + 'ms';} function testloop2 () {var somearray = new array (); for (VAR I = 0; I <50000; I ++) {somearray. push (I);} var starttime = new date (); For (VAR J = 0, looplen = somearray. length; j <looplen; j ++) VaR value = somearray [J]; document. getelementbyid ('divshowtime2 '). innerhtml = 'time consumed 2: '+ (new date ()-starttime) + 'ms ';}
This article is also easy to understand. The first method requires more steps to get the array length than the second method.
15. Add Cache Control expiration and maximum survival time tags to the HTTP header information.
Not supplemented
16. Optimize CSS. Use the <link> method instead of the @ import method. Please refer to this excellent document http://www.slideshare.net/stubbornella/object-oriented-css
Not supplemented
17. Use CSS technology to optimize image resources
Reduces the number of image links and network transmission pressure.
18. Use gzip to compress. js and. CSS files. If you are using Apache, set the compression method in. htaccess. Your HTML, XML, and JSON will also be compressed.
Addoutputfilterbytype deflate text/HTML text/CSS text/plain text/XML application/X-JavaScript Application/JSON
Reduces the transmission pressure and increases the response speed. For small websites, JS and CSS files are not very large, and the effect is not obvious.
19. use JavaScript compression tools. In addition to using Yui and jsmin, you can also try Google closure http://closure-compiler.appspot.com/home (thanks to James Westgate, a reader)
Similar to the above, there are many JS compression and obfuscation tools.
20. Optimize various resources on each page and split them into subdomains so that they can be downloaded in parallel. See http://yuiblog.com/blog/2007/04/11/performance-research-part-4/
Not supplemented.
21. Place the CSS style sheet at the top of the page to facilitate resolution by browsers including IE.
Not supplemented.
22. Try to keep the DOM structure as simple as possible. The volume of Dom affects the efficiency of related operations, such as search, traversal, and Dom changes. Document. getelementsbytagname ('*'). The smaller the length value, the better.
Not supplemented.
23. Pay attention to the selector you are using. For example, if you want to obtain a direct sub-element under ul, use jquery ("Ul> li") instead of jquery ("Ul li ")
Faster search speed with fewer traversal elements.
24. when you switch the visibility of elements (Display), remember: element.css ({display: None}) is faster than element. hide () and element. addclass ('mydendenclass '). Unless in a loop, I select element. addclass ('myhiddenclass'), which will make the code more concise-do not use inline CSS and JavaScript.
Not supplemented.
25. After using the reference variable for Dom, you should set it to null.
Reclaim resources.
26. When Ajax is used, the get execution efficiency is higher than that of post. Therefore, try to use the get method. Note that IE only allows you to transmit 2 k Data with get.
Because the same information is transmitted in get mode and less data is used, the get method is highly efficient. However, the get method is not highly secure, and the amount of data transmitted is limited.
27. Use script animation with caution. Without hardware support, the animation will be executed very slowly. Try to avoid animation effects that have no practical value.
This is a deep understanding of every script animation that has been used. However, I think canvas in HTML5 will be widely used. Canvas can make fascinating animation effects, which deserves your attention.
28. If your background-image container for this image is too small, avoid using background-repeat. If your background image needs to be filled back and forth many times to fill the background, it is unwise to set the background-repeat attribute to background-image, repeat-X, or repeat-y to fill the background, this filling method is very inefficient. You should try to use a large enough image for background-image and use background-repeat: No-repeat.
Good suggestion, not supplemented
29. Do not use <Table> for layout. <Table> You need to draw it multiple times before the browser completely draws it. In Dom, <Table> is a rare element that affects the Display Effect of the previous output. For Table data, you can use table-layout: fixed;, which is a more effective reality.AlgorithmAccording to the CSS 2.1 technology, this method can output a row in a table.
In addition to the above reasons, table has many strange differences in style inheritance and offset value calculation in the performance of multiple browsers. For example, if there is an element DIV in TD, the offsetparent of the Div returns the TD element, not the parent element with the position attribute we expected.
30. Try to use the original JavaScript as much as possible. Restrict the use of JavaScript frameworks.
the principle depends on the actual situation. If the project is very small, most of the Code in the framework is useless if the framework is used, in this way, the loading time is increased. For large projects, mature frameworks such as jquery can be used to reduce the development time and cost, as well as the subsequent maintenance cost.