Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find('a,b') is slower than find('a')+find('b'), why?

jsperf's link

I'm not a jQuery expert(not even a good user), i haven't studied the whole source code of it (only a little part which can't help me solve this problem).

Can somebody explain this for me?

like image 791
rhapsodyn Avatar asked Oct 10 '11 12:10

rhapsodyn


1 Answers

This:

$p.find("input,select");

...uses the native querySelectorAll.

This:

$p.find("input");
$p.find("select");

...uses the native getElementsByTagName.

The getElementsByTagName is simply faster, perhaps because it is a very simple selection, and has been around longer, giving it more time for optimization.

Also, when jQuery uses querySelectorAll, it does so from the document even if you're searching from a specified context, so this has an impact. To narrow the results to the context you provided, it changes your selector to use the ID of the element, or gives it a temporary one if non exists.


I updated your test to give a few more comparisons. Shows that if you're really concerned about performance, you should use the native API.

like image 101
user113716 Avatar answered Sep 20 '22 04:09

user113716