开发者

jQuery single selector vs .find()

Which is better to use as a performa开发者_开发知识库nce perspective:

$(".div1 h2, .div1 h3")

or

$(".div1").find("h2, h3")


http://jsperf.com/selector-vs-find-again

selector is faster

(NOTE: made up random html just so it wasn't just those elements on the page)


The answer to your question is: yes.

Don't worry about the performance difference, unless your code is slow. If it is, use a profiler to determine bottlenecks.

From an analysis standpoint:

$(".div1 h2, div1 h3")

should be faster as jQuery will pipe it through querySelectorAll (if it exists) and native code will run faster than non-native code. It will also save on an additional function call.

$(".div1").find("h2, h3")

is better if you plan on chaining some other functions on .div1:

$(".div1").find("h2, h3").addClass('foo').end().show();


Actually, .find() CAN be faster.

Selectors seem to be quicker over find when trying to select multiple elements; however, if you use a $.find, or even cache the descendant, you can see it's much faster: http://jsperf.com/selector-vs-find-again/11

I also beg to differ about performance not being important. In this world of smart phones, battery life is king.


I've just found this answer and want to add some numbers here, may be someone find them helpful and curious. In my case I looked for fastest jQuery selector for unique element. I don't like to add IDs without reason, so I looked for way to select elements without ID.

In my small research I used awesome selector profiler for jQuery. And here is the code I fired up directly from Chrome console after I added profiler's library code:

$.profile.start()
// Lets 
for (i = 0; i < 10000; i++) {

  // ID with class vs. ID with find(class)
  $("#main-menu .top-bar");
  $("#main-menu").find(".top-bar");

  // Class only vs element with class
  $( ".top-bar" );
  $( "nav.top-bar" );

  // Class only vs class-in-class
  $( ".sticky" );
  $( ".contain-to-grid.sticky" );
}
$.profile.done()

Here are results:

jQuery profiling started...
Selector                  Count  Total Avg+/-stddev  
#main-menu .top-bar       10000  183ms 0.01ms+/-0.13 
nav.top-bar               10000  182ms 0.01ms+/-0.13 
.contain-to-grid.sti...   10000  178ms 0.01ms+/-0.13 
.top-bar                  10000  116ms 0.01ms+/-0.10 
.sticky                   10000  115ms 0.01ms+/-0.10 
#main-menu                10000  107ms 0.01ms+/-0.10 
undefined

Slowest selectors are on the top of this chart. Fastest ones are at the bottom. Surprisingly for me right after selector by ID i.e. $('#main-menu') I've found single class selector e.g. .top-bar and .sticky. Cheers!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜