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 co开发者_开发知识库de of it (only a little part which can't help me solve this problem).
Can somebody explain this for me?
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.
What Ӫ_._Ӫ said above is true, but do note that the results aren't necessarily equivalent, since the first will (AFAIK) return input
s and select
s in interspersed document order and the second will return them one after each other. This may not matter for your application, but it's something to note.
精彩评论