tester
tester

Reputation: 23149

Fastest way to build this string

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('');

Upvotes: 1

Views: 6958

Answers (5)

Purag
Purag

Reputation: 17061

This does the trick too:

var items = [
    {html: '<div>test</div>'},
    {html: '<div>test</div>'},
    {html: '<div>test</div>'}],
    newString = "";
items.forEach(function(item) {
    newString = newString + item.html;
});

Demo.

Upvotes: 0

user1150525
user1150525

Reputation:

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);

Upvotes: 2

qw3n
qw3n

Reputation: 6334

Warning this is solution could cause a lot problems. But it does give a relatively fast way to do what you want.

var items = [{
    html: '<div>test</div>'
}, {
    html: '<div>test</div>'
}, {
    html: '<div>test</div>'
}];

Object.prototype.toString=function(){return this.html};

items.join('');

If there is anyway to control the object that gets added to the array in the first place then you can change only that object's prototype which won't mess with the global Object.

Upvotes: -1

Brian
Brian

Reputation: 3023

var html = '';
for (var i = 0, itemLen = items.length; i < itemLen; i++) {
    html += items[i].html;
}
output.innerHTML = html

Simply concatenating to a string would be faster than building an array and imploding it as that technically double loops the data instead of looping it once.

Upvotes: 1

Starx
Starx

Reputation: 78971

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;

Upvotes: 1

Related Questions