Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 289
Krzysztof Romanowski Avatar asked Nov 23 '11 15:11

Krzysztof Romanowski


1 Answers

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.

like image 75
Frédéric Hamidi Avatar answered Oct 04 '22 22:10

Frédéric Hamidi