开发者

When creating new element in jQuery, is there a method that is faster?

Is there a way that has better performance than the other when appending a new element to the dom with jQuery?

This is the way I usually do it:

$('<div class="foo">Hello World!</div>').appendTo($("#bar"));

But I've seen this quite a few times around :

$('<div/>').attr("class", "foo").text("Hello World!").appendTo($("#bar"));

I think that the first one is easier to read. Second one takes advantage of chaining but it in the end, the result is the same. But is it f开发者_开发知识库aster to do it one way of the other?


As you can see here: http://www.jsfiddle.net/SvCTK/

the difference in performance is pretty trivial (maybe not that trivial, find out for yourself). Source for benchmark:

var loop = 1000,
    $bar = $('#bar');

console.time('first')
while(loop--){
    $('<div class="foo">Hello World!</div>').appendTo($bar);
}
console.timeEnd('first');

loop = 1000;
$bar.html('');

console.time('second')
while(loop--){
   $('<div/>').attr("class", "foo").text("Hello World!").appendTo($bar);
}
console.timeEnd('second');

You need a open FireBug or Webkit developers tools to see the results.


The first one is faster because it does not have to deal with extra call of attr function.


Both ways are fine, however the first will be a little quicker due to it using less methods. So instead of just using .appendTo you are using .attr, .text, and .appendTo.


You comparison isn't quiet accurate. If your code was adding attribute values to targeted elements then you'd have the same number of function calls. I'm pretty sure they are equivalent approaches.

Editorial:

JQuery is written using the concept of a fluent interface which is what enables the chaining of method calls. It is equivalent code as writing each step out in a more step-by-step way.


document.createElement() is technically the fastest method to create DOM elements. However, the amount of time saved is typically trivial.

$(document.createElement('div'))
    .attr('class', 'foo')
    .text("Hello World!")
    .appendTo("#bar");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜