60

Which is better to use as a performance perspective:

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

or

$(".div1").find("h2, h3")
Cristian Sanchez
  • 31,171
  • 11
  • 57
  • 63
Dan
  • 2,321
  • 3
  • 27
  • 40
  • 7
    To find that out you could profile your code: http://jsperf.com/ – Felix Kling Jun 03 '11 at 17:03
  • 2
    See [this answer](http://stackoverflow.com/a/12177876/323407) for a non-performance-related but important difference. Personally I wouldn't worry about microsecond differences unless the code will run in a loop or you are writing a library which will be used by third parties. – Tgr Aug 30 '12 at 21:52
  • the problem is often the same, 10⁶ x 1microsec makes 1sec :) – Bill'o Apr 04 '14 at 08:13
  • 2
    https://learn.jquery.com/performance/optimize-selectors/ (this logic can also be applied to native selectors) – Christophe Roussy Jul 06 '20 at 09:42

4 Answers4

50

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)

James Montagne
  • 77,516
  • 14
  • 110
  • 130
  • 21
    This is the actual answer; instead of just "it doesn't matter". It matters because OP asked. – JustKash Aug 23 '13 at 22:50
  • do you have any element about what makes it faster ? I would have instinctively thought the find to be faster. So I'm curious what makes it slower. – Ar3s Jun 09 '14 at 23:40
  • 1
    @Ar3s zzzzBov's answer mentions it. If a browser supports `querySelectorAll` that will be used and that is faster. – James Montagne Jun 10 '14 at 00:41
  • Great job... Really proves which one is faster. – Md. Alim Ul Karim Nov 05 '14 at 19:09
  • 5
    I got this... `selector` - 35,349 - ±1.47% - 43% slower `find` - 62,415 - ±2.58% - fastest With the other test( http://jsperf.com/single-selector-vs-find ) where it has `.hide()` chained, I got almost opposite.. find being 52% slower.. Can someone explain? – Praveen Puglia Nov 14 '14 at 08:59
  • Using simple selectors is the fastest, even if it requires combining. http://jsperf.com/selector-vs-find-again/52 – Semra Nov 14 '14 at 13:35
  • 3
    Actually find is faster according to this test in the most current version http://jsperf.com/selector-vs-find-again/60 especially in simple finds – nilveryboring Feb 12 '15 at 00:13
  • @nilveryboring It's still the same for the original selector in the question. interesting that it's different with a simpler selector. – James Montagne Feb 12 '15 at 14:39
  • Okay, but what if we already have "```var $myVariable = $('.div1');```" for some other requirement(s), would "`$myVariable.find('h2, h3')`" be faster than full-selector? – Top-Master Mar 24 '22 at 18:48
  • Now .find() is faster. Check the official doc: https://learn.jquery.com/performance/optimize-selectors/ – Blodhgard Dec 07 '22 at 14:30
  • @Blodhgard I wonder where in that documentation you've found that .find() is faster. Here https://learn.jquery.com/performance/optimize-selectors/#save-calls-to-queryselectorall it says to just use the single selector as it will reduce querySelectorAll() calls. – Rick Aug 30 '23 at 08:31
38

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();
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • 1
    "slow" to me means more than approx `0.3s` for most JS functions. There's no way I'd let the browser hang for 1s, much less 10. If it passes my "slow threshold" I'd refactor the code and analyze performance. – zzzzBov Jun 03 '11 at 17:21
  • Yes, you are right, in this case performance difference isn't a big deal. But be careful with that sentence. I am kinda traumatized for seeing several performance issues and people thinking "if it works I don't care any more"... – BrunoLM Jun 03 '11 at 17:25
  • 1
    what I meant by my statement was that you shouldn't worry about performance unless it is a problem. I never said sloppy code was ok, but I don't mind an O(n^3) set of loops if they are understandable and aren't causing performance issues. If they did, I'd certainly work to reduce them to as close to O(n) as possible. – zzzzBov Jun 03 '11 at 17:28
  • 1
    @BrunoLM: I agree about being careless. There is no harm in obtaining good habits and if they happen to increase performance not matter how small even beeter. Making something a good habit does not increase development time but does save time on performance tuning later if it is required. – Nope Aug 29 '12 at 12:19
17

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.

Drath
  • 325
  • 3
  • 7
  • This is interesting, but in this case it will not search for the `h2` and the `h3` that are only descendant of `div1`. – Dan Jan 04 '13 at 12:38
  • @Dan The "find cache" actually uses div1, but just caches it above like: `var cache = $(".div1");` That being said, Firefox doesn't seem to think that one is faster. In that case, you're correct, the "speed find" will find all `h2` `h3`, but it's simple to give them classes directly like: `$.find(".classh2, .classh3")` to target specific ones. – Drath Jan 04 '13 at 14:13
2

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!

sashaegorov
  • 1,821
  • 20
  • 26