开发者

Which is better: string html generation or jquery DOM element creation?

Ok, I'm rewriting some vanilla JS functions in my current project, and I'm at a point where there's a lot of HTML being generated for tooltips etc.

My question is, is it better/preferred to do this:

var html 开发者_C百科= '<div><span>Some More Stuff</span></div>';
if (someCondition) {
    html += '<div>Some Conditional Content</div>';
}
$('#parent').append(html);

OR

var html = $('<div/>').append($('<span/>').append('Some More Stuff'));
if (someCondition) {
    html.append($('<div/>').append('Some conditionalContent');
}
$('#parent').append(html);

?


From a performance standpoint: it depends.

In your short example, it's faster to append the text, since you actually aren't creating any DOM elements until the end. However if you were doing this a lot, then the added time of string concatenation vs the performance of cached document fragments adds up.

When you do $(html) jQuery caches it as a document fragment (provided the string is 512 bytes or less), though there's not much gain if you're caching just $("<div />")...however if you're doing it thousands of times, there is a measurable impact, as string concatenation gets more expensive as your string gets longer, the cached document fragment cost is pretty steady.

Update: Here's some quick examples to see what I mean, use firebug to get the console times here:

You can run this for yourself: http://jsfiddle.net/Ps5ja/

console.time('concat');
var html = "";
for(var i = 0; i < 500; i++) {
    html += '<div><span>Some More Stuff</span></div>';
    html += '<div>Some Conditional Content</div>';
}
var elem = $(html);
console.timeEnd('concat'); //25ms

console.time('DOM');
var parent = $("<div />")
for(var j = 0; j < 500; j++) {
    parent.append($('<div/>').append($('<span/>', {text :'Some More Stuff'})));
    parent.append($('<div/>',{ text: 'Some conditionalContent' }));
}
console.timeEnd('DOM'); //149ms

console.time('concat caching');
var html = "";
for(var i = 0; i < 5000; i++)
    html += '<div><span>Some More Stuff</span></div><div>Some Conditional Content</div>';
var elem = $(html);
console.timeEnd('concat caching'); //282ms

console.time('DOM caching');
var parent = $("<div />")
for(var j = 0; j < 5000; j++)
    parent.append('<div><span>Some More Stuff</span></div><div>Some Conditional Content</div>');
console.timeEnd('DOM caching'); //157ms

Note: the var elem = $(html); in the string test is so we end up creating the same DOM elements, otherwise you're comparing string concatenation to actual DOM creation, hardly a fair comparison, and not really useful either :)

You can see by the above, as the cached fragment is more complex, the more caching makes an impact. In the first test, which is your example without the condition cleaned up a bit, DOM loses because there are lots of little operations going on, in this test (on my machine, but your ratios should be about the same): HTML Contact: 25ms, DOM Manipulation: 149ms.

However, if you can cache the complex fragment, you get the benefit of not creating those DOM elements repeatedly, just cloning them. In the second test DOM wins out, because while the HTML method creates that DOM element collection 5000 times, the second cached method only creates it once, and clones it 5000 times. In this test: HTML Concat: 282ms, DOM Manipulation: 157ms.

I realize this isn't directly in response to your question, but based on comments it seems there's some curiosity about performance, so just giving something you can see/test/play with.


I have tested the code Nick Craver has submitted and have found that DOM caching works faster only if the content of the element does not change. If you however alter the string in each iteration of the for loop, the speed dramatically decreases.

Here's the same code modified (test it on Fiddle: http://jsfiddle.net/Ps5ja/42/)

console.time('concat');
var html = "";
for(var i = 0; i < 500; i++) {
    html += '<div><span>Some More Stuff</span></div>';
    html += '<div>Some Conditional Content</div>';
}
var elem = $(html);
console.timeEnd('concat');

console.time('DOM');
var parent = $("<div />")
for(var j = 0; j < 500; j++) {
    parent.append($('<div/>').append($('<span/>', {text :'Some More Stuff'})));
    parent.append($('<div/>',{ text: 'Some conditionalContent' }));
}
console.timeEnd('DOM');

console.time('concat caching');
var html = "";
for(var i = 0; i < 10000; i++)
    html += '<div><span>Some More Stuff</span></div><div>Some Conditional Content'+i+'</div>';
var elem = $(html);
console.timeEnd('concat caching');

console.time('concat array.join');
var arr = [];
for(i = 0; i < 10000; i++)
    arr.push('<div><span>Some More Stuff</span></div><div>Some Conditional Content'+i+'</div>');

var elem = $(arr.join(''));
console.timeEnd('concat array.join');

console.time('DOM caching - NO modification');
var parent = $("<div />")
// here the contained text is unchanged in each iteration
for(var j = 0; j <10000; j++)
    parent.append('<div><span>Some More Stuff</span></div><div>Some Conditional Content</div>');
console.timeEnd('DOM caching - NO modification');

console.time('DOM caching with modification');
var parent = $("<div />")
// here the contained text is modified in each iteration
// (the value od J is appended to the text)
for(var j = 0; j <10000; j++)
    parent.append('<div><span>Some More Stuff</span></div><div>Some Conditional Content'+j+'</div>');
console.timeEnd('DOM caching with modification');

The conclusion is that DOM caching works faster only if you plan to replicate the same HTML fragment over and over. If not go with the string concatenation.

I haven't found any speed benefits in using Array.join method. However I haven't tested that thoroughly (it might be that changes if the number of iterations is bigger).


Favour DOM manipulation over innerHTML methods. For one thing, DOM manipulation will correctly handle characters that need to be escaped with innerHTML. For another, it is typically faster, sometimes much faster.


In general, if I have a lot of html to generate, I collect it all in one string and let the browser generate the elements all at once.

If there will be lots of conditionals or loops involved, then you may want to use Array.join() instead of string concatenation with +. With string concatenation the browser will generate lots of intermediate strings which can be very slow; Array.join() skips all those intermediate strings. For these cases I'd do something like:

var html = ['<div><span>Some More Stuff</span></div>'];
for (var i = 0; i < 1000; i++) {
    html.push('<div>Some Loop Content</div>');
}
$('#parent').append(html.join(''));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜