iambriansreed
iambriansreed

Reputation: 22241

Which jQuery selection is more efficient?

Which set of selectors is more efficient?

1

$('#parent_element span.class1').do_something1();
$('#parent_element span.class2').do_something2();
$('#parent_element span.class3').do_something3();
$('#parent_element span.class4').do_something4();

2

$parent_element = $('#parent_element'); 
$parent_element.find('span.class1').do_something1();
$parent_element.find('span.class2').do_something2();
$parent_element.find('span.class3').do_something3();
$parent_element.find('span.class4').do_something4();

My guess is #2 is more effecient as it begins a search find() focused on the parent element vs the entire DOM. Is this true?

If so how many calls to that parent element would be needed to make it more efficient than #1?

Thanks!

Upvotes: 3

Views: 117

Answers (2)

jfriend00
jfriend00

Reputation: 707218

As with anything like this, you MUST test with a tool like jsperf if you want the real answer. The test shows that the second is much faster than the first.

If they were all the same method calls or you could process each one in a .each(fn) method, you could combine them all like this and the selector operation would be significantly faster:

$('#parent_element').find('span.class1, span.class2, span.class3, span.class4').each(fn);

enter image description here

You can run it yourself here: http://jsperf.com/selector-options. Your first option is the orange. Your second option is the blue. The combined selector is the red. The cached parent is about 30-80% faster. If they can all be combined into one selector, it's multiple times faster.

Upvotes: 5

Paolo Bergantino
Paolo Bergantino

Reputation: 488384

Solution #2 is wildly more efficient. Caching selectors in jQuery is one of the best ways to cut down on the time it takes to do selections. For any uses greater than 1, go with solution 2.

Upvotes: 7

Related Questions