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!
source to share
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);
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.
source to share