March 2, 2012
Fastest way to build this string
Question by tester
say I have an array of objects with html strings inside (there are other things, but i’m specifically focusing on the html property of each object. e.g.
var items = [{
html: '<div>test</div>'
}, {
html: '<div>test</div>'
}, {
html: '<div>test</div>'
}];
I need to build a string using all of these strings and I need them in the same order they’re given to me, so a reverse while loop is out.
is there anything faster at building the html than the following?
var html = [];
for (var i = 0, itemLen = items.length; i < itemLen; i++) {
html.push(items[i].html)
}
output.innerHTML = html.join('');
Answer by user1150525
faster would be:
var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; ++i)
html += items[i].html;
output.innerHTML = html;
Edit:
This is faster:
var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; html += items[i++].html);
Answer by Starx
This is much faster than yours
var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; i++) {
html += items[i].html;
}
output.innerHTML = html;