Fastest way to build an HTML string

You have a massive array of items that needs to be transformed into an HTML list without causing the user any grief. There are a couple common ways of doing this:
Note: I’m not even going to bother covering direct DOM manipulation for every list item because that’d be plain stupid!
#1 - Step-by-step string concat
Not the slowest method that exists but probably the most common:

var arr = ['item 1', 'item 2', 'item 3', ...],
    list = '';
 
for (var i = 0, l = arr.length; i < l; i++) {
    list += '<li>' + arr[i] + '</li>';
}
 
list = '<ul>' + list + '</ul>';


Don’t use this. It’s inefficient, slow and ugly!
#2 - Step-by-step array pushing
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] + '</li>';
}

list = '<ul>' + list.join('') + '</ul>';


Slightly faster than string concatenation but still not perfect…
#3 - The holy grail!
var arr = ['item 1', 'item 2', 'item 3', ...];
 
var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

I won’t bore you with benchmarks; you’ll just have to believe me (or test for yourself) - this is by far the fastest method!
Using native methods (like join()), regardless of what’s going on behind the abstraction layer, is usually much faster than any non-native alternative.
Browser benchmarks
Due to a request and my own curiousity I’ve conducted a quick benchmarking test. Each method was tested with a 130-item array, the length of each item varied so any optimizations on the browser’s part would not be effective. Each method was tested 1000 times; the results below show how long each browser took to complete each method 1000 times:
“String concat” (ms) “Array pushing” (ms) “Native join()” (ms)

Firefox 3	147	148	65
Opera 9	172	125	78
IE 7	500	2297	79
Chrome 2	63	88	72
Safari 4b	146	141	60
Averages	205	559	70

Surprisingly, string concatenation came out much faster than “array pushing” on average. It seems IE7 optimizes for lengthy string operations but doesn’t care much for arrays. Also, Google Chrome performed oddly; the “string concatenation” method was quicker than the “native join()”… I’m not too sure what’s going on there! Anyway, the results were mostly predictable, and, of course, “native join()” came out on top!

你可能感兴趣的:(JavaScript,html,chrome,IE,Safari)