jQuery single selector vs .find()
JavascriptJqueryJquery SelectorsJavascript Problem Overview
Which is better to use as a performance perspective:
$(".div1 h2, .div1 h3")
or
$(".div1").find("h2, h3")
Javascript Solutions
Solution 1 - Javascript
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)
Solution 2 - Javascript
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();
Solution 3 - Javascript
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.
Solution 4 - Javascript
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!