jQuery is quite multifaceted when it comes to selecting certai开发者_Go百科n DOM elements. Today it came to my attention that the two ways of getting the same elements may yield different speed:
$("selector1").find("selector2").find("selector3")
and
$("selector1 selector2 selector3")
(where selectorX
can be ID or class or anything else)
Both produce the same set of elements but are there any speed differences? How does jQuery actually traverse DOM? This is especially important in the second case: does it go from selector1 to selector3 or the other way around?
Anybody measured the difference between the two?
Using a single $('...')
is about twice as fast as chaining $.find()
s for me in Chrome. This JSPerf Benchmark will give you a good idea of other browsers as well once some more people test it.
Time it yourself and find out!
console.time("Selector 1")
$("selector1").find("selector2").find("selelector3");
console.timeEnd("Selector 1")
console.time("Selector 2")
$("selector1 selector2 selector3");
console.timeEnd("Selector 2")
There is a difference between the two if you are using classes. $("selector1 selector2 selector3")
is going to be slower in IE if any (or all) of the selectors are classes because of the lack of support for document.getElementByClassname. Also in IE $("selector1").find("selector2").find("selector3")
will be slower if selector1 is a class (for the same reason as before). I don't think you will find a cross browser timing due to the different methods available to jQuery code in IE vs FF.
After reviewing the findings from @jcm, I decided to test a bit further into these selectors. I went in with the assumption that a more complex DOM structure would produce much different results.
Here are the tests I created http://jsperf.com/complex-dom-jquery-selectors-vs-traversal-methods
This uses the latest jQuery (v1.6). It seems that .find()
is leaps and bounds faster than the other methods of traversal. This is very interesting news. For a long time, many users of jQuery (including myself) have offered up the advice that one should use traversal methods, (and typically avoid the find method) instead of selector strings. So much for that!
I guess the lesson to learn here is that, when absolute performance is a must, rather than depending solely on historical evidence, test your hypotheses.
精彩评论