Which jQuery choice 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 # 2 is more efficient as it starts searching find()

targeting the parent element and the entire DOM. It's true?

If so, how many calls will it take to this parent to make it more efficient than # 1?

Thank!

+3


source to share


2 answers


Solution # 2 is much more effective. JQuery caching selectors are one of the best ways to reduce the time it takes to select. For any use greater than 1, go to solution 2.



+7


source


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

If there were all the same method calls, or you could handle each of them in a method .each(fn)

, 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 here: http://jsperf.com/selector-options . Your first choice is orange. The second option is blue. The combo selector is red. The cached parent is about 30-80% faster. If they can all be combined into one selector, it will be several times faster.

+4


source







All Articles