JQuery - Why is creating an object with a class per line ($ ('<div class = "foo" / ">')) slower than creating the same object and executing the addClass () method?
Can someone explain to me why creating an object through a string is slower than the same object and execute the addClass () method in jQuery?
I thought the addClass () method would be slower, but that is not the case. I wonder why?
Take a look at this jsPerf - http://jsperf.com/jquery-append-with-class-and-with-method-addclass
This is because only passing the element name, for example $("<div>") , maps to calling document.createElement () .
On the other hand, passing an element and its attributes, such as $("<div class='foo'>") , matches a call to document.createDocumentFragment () , which is slower than createElement() , followed by an entry in the className property.
I tried adding a third test case with
viaObject = $("<div>", { class: "foo-"+counterN }); biz.append(viaObject); counterN++; which I thought should have been as fast as $("<div>").addClass("foo-") for the reason noted by Frederick Hamidi (document.createElement () vs document.createDocumentFragment ()), but still slower.
AddClass () is probably faster than accessing object properties.
In any case, this proves that you must create your element as follows
$("<div>", { class: "foo-"+counterN }); and not so:
$('<div class="foo-' + counterS + '" />');