// Modify the following JavaScript code for the connection string to a more efficient way var htmlstring = ' < div class= ' container ' > ' + ' < ul id= ' news-list ' > '; for (var i = 0; i < news.length; i+++ = ' < li > < a href= "' +news[i]. LINK + ' "> +news[i]. TITLE + ' < a > </li >+ = ' </ul > </div > ';
There are two test centers:
- The connection mechanism for JavaScript strings.
- Large-scale loop body is the key optimization object
First look at the 1th, the connection mechanism of the string
var str;
str = ' This is a string ';
str = str + ', another string. ';
The processing mechanism for this connection operation JS is:
(1) Create a new temporary string,
(2) Assign the new string to STR + ', another string. ', and return this new string
(3) and destroy the original string at the same time
Therefore, the connection efficiency of the string is low. The way to improve efficiency is to use the Join function of the array, using join instead of string concatenation this technique has significant performance gains for IE6, 7, and no significant performance loss for modern browsers
2nd, large-scale cycle bodies are the main optimization objects
In JavaScript, we can use for(;;) , while() for(in) three loops, in fact, these three loops in the efficiency of the very poor, because it needs to query hash key, as long as it can, should be used sparingly. for(;;)and while loops, while loops are more efficient than for(;;) , because for(;;) of structural problems, need to jump back often. The usual loop optimizations will loop backwards, and the most commonly used for and while loops are pre-test loops, which, like Do-while, can avoid the calculation of the initial termination condition and therefore run faster.
var arr = [1, 2, 3, 4, 5, 6, 7]; var sum = 0; for (var i = 0, L = arr.length; i < L; i++) { + = arr[i] ; } // you can consider replacing it with the following: var arr = [1, 2, 3, 4, 5, 6, 7]; var sum = 0, L = arr.length; Do { + = arr[l]; } while (l--)
News.length need to cache, reduce each cycle to access the property, or each cycle will have to recalculate the length
Using local variables for news,news[i] is efficient:
var item =news[i].
News[i]. LINK-> item. LINK
News[i]. TITLE-> item. TITLE
After the above two steps optimization, the final program is
var htmlstring=[];
Htmlstring.push ("< div class= ' container ' > < ul id= ' news-list ' >");
This is to maintain the order of stitching, so use i++ instead of len--notation for (var i=0,len=news.length; i<len;i++) { var item = News[i];
htmlstring. Push (' < li > < a href= "' +item.link + '" > +item.title + ' </> </li > ');
}
Htmlstring.push (' </ul > </div > ');
Htmlstring=htmlstring.join ("");
JS String Stitching Optimization