jQuery - Why creating object with class by string ($('<div class="foo" />')) is slower than creating same object and execute addClass() method?
Asked Answered
N

3

6

Can anyone may explain me why creating object via string is slower than same object and execute addClass() method in jQuery?

I thought that addClass() method will be slower, but it is not. I'm wondering why?

Look at this jsPerf - http://jsperf.com/jquery-append-with-class-and-with-method-addclass

Narcisanarcissism answered 23/11, 2011 at 15:43 Comment(0)
V
4

That's because only passing an element name, like $("<div>"), maps to a call to document.createElement().

On the other hand, passing an element and its attributes, like $("<div class='foo'>"), maps to a call to document.createDocumentFragment(), which is slower than createElement() followed by a write to the className property.

Vacillating answered 23/11, 2011 at 15:54 Comment(3)
Good point. Does this apply to the $("<div>", {"class":"foo"}) approach as well? Looking at the benchmarks it's still slower than .addClass().Eyot
This also applies to that code (it will result in a call to createElement()), but iterating over a hash of attributes and performing the associated calls to attr() is still slower than a single call to addClass().Tredecillion
Thanks guys, now I know. Besides for me (Chrome 15 on MAC) adding class via {} take the same time as .addClass()Narcisanarcissism
M
3

I would say that $('<div class=“foo” />') takes time because it has to parse the HTML string, then perform the addClass() (or internal equivalent) anyway.

Madrid answered 23/11, 2011 at 15:47 Comment(0)
R
0

I tried adding a third test case with

viaObject = $("<div>", { class: "foo-"+counterN });
biz.append(viaObject);
counterN++;

that i thought should have been as fast as $("<div>").addClass("foo-") for the reason pointed out by Frédéric Hamidi (document.createElement() vs document.createDocumentFragment()) but it still slower.

Probably addClass() is faster than accessing properties of an object.

In any case this proves that you should create your element like this

 $("<div>", { class: "foo-"+counterN }); 

and not like this:

 $('<div class="foo-' + counterS + '" />');
Roye answered 23/11, 2011 at 16:1 Comment(1)
Yup. See comments in Frederic's answer.Eyot

© 2022 - 2024 — McMap. All rights reserved.