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

StackOverflow https://stackoverflow.com/questions/8245012

  •  07-03-2021
  •  | 
  •  

سؤال

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

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

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 + '" />');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top