Fastest way to build a HTML stringposted in ' Code Snippets, JavaScript ' by James on May 29th, 2009
Original: http://james.padolsey.com/javascript/fastest-way-to-build-an-html-string/
Copy Code code 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 least efficient way.
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 one on the way.
var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...]; var list = ' <ul><li> ' + arr.join (' </li><li> ') + ' </li></ul> '/best way.
Performed 1000 times: "String concat"
(MS)
"Array pushing"
(MS)
"Native Join ()"
(MS)
Firefox 314714865Opera 917212578IE 7500229779Chrome 2638872Safari 4b14614160averages20555970
Only Chrome is more special, the first is the fastest.
Chinese Translation version
First: adding Strings by string
Copy Code code 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 lowest efficiency! Code logic is relatively complex.
The second type: Push into the array one by one
Copy Code code 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's a little bit quicker than the last one, but it's not good enough ...
The third type: Direct join ()
Copy Code code as follows:
var arr = [' Item 1 ', ' Item 2 ', ' Item 3 ', ...];
var list = ' <ul><li> ' + arr.join (' </li><li> ') + ' </li></ul> ';
Using native methods (such as join ()), regardless of how it is implemented later, is generally much faster than other methods, and the code is very concise.
Using native methods (such as join ()), regardless of how it is implemented later, is generally much faster than other methods, and the code is very concise.
Browser performance
Each method is tested with an array of length 130, each of which has a variety of lengths, preventing browsers from making special optimizations to a certain length of string, 1000 tests per method, and the following results: The time required to perform these 1000 times