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;

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!