Fastest way to build an HTML stringPosted in 'Code Snippets, JavaScript 'by James on May 29th, 2009
Original article: http://james.padolsey.com/javascript/fastest-way-to-build-an-html-string/
Copy codeThe Code is as follows: var arr = ['item 1', 'item 2', 'item 3',...],
List = '';
For (var I = 0, l = arr. length; I <l; I ++ ){
List + = '<li>' + arr + '</li> ';
}
List = '<ul>' + list + '</ul>'; // the most inefficient method.
Var arr = ['item 1', 'item 2', 'item 3',...], list = []; for (var I = 0, l = arr. length; I <l; I ++) {list [list. length] = '<li>' + arr + '</li>';} list = '<ul>' + list. join ('') + '</ul>'; // faster than the previous method.
Var arr = ['item 1', 'item 2', 'item 3',...]; var list = '<ul> <li>' + arr. join ('</li> <li>') + '</li> </ul>'; // optimal method.
Run 1000 times: "String concat"
MS)
"Array pushing"
MS)
"Native join ()"
MS)
Firefox 314714865 Opera 917212578IE 7500229779 Chrome 2638872 Safari 4b14614160Averages20555970
Only chrome is special. The first method is the fastest.
Chinese translation version
First: Add strings one by oneCopy codeThe Code is as follows: var arr = ['item 1', 'item 2', 'item 3',...],
List = '';
For (var I = 0, l = arr. length; I <l; I ++ ){
List + = '<li>' + arr [I] + '';
}
List = '<ul>' + list + '</ul> ';
This is the most common, but the most efficient! The Code logic is relatively complex.
Type 2: push the data to the array one by oneCopy codeThe Code is as follows: var arr = ['item 1', 'item 2', 'item 3',...],
List = [];
For (var I = 0, l = arr. length; I <l; I ++ ){
List [list. length] = '<li>' + arr [I] + '';
}
List = '<ul>' + list. join ('') + '</ul> ';
It is a little faster than the previous method, but it is not good enough...
Third: Direct join ()Copy codeThe Code is as follows: var arr = ['item 1', 'item 2', 'item 3',...];
Var list = '<ul> <li>' + arr. join ('</li> <li>') + '</li> </ul> ';
The use of native methods (such as join (), no matter how it is implemented later, is generally much faster than other methods, and the code is very concise.
Use native methods (suchJoin ()), No matter how it is implemented, it is generally much faster than other methods, and the code is very concise.
Browser Performance
Each method uses an array with a length of 130 for testing. The length of each element is varied to prevent the browser from making special Optimizations to strings of a certain length; each method is tested for 1000 times. The following results show the time required to perform the 1000 times: