Any time you can use an ID selector it will be faster. jQuery selector engine (Sizzle) reads from right to left. The only exception being if on the far left is an id
, then that id
is used to scope the search.
Additionally, since jQuery uses native browser functionality wherever possible, always supply the tag name when using a class selector.
In your series of options as to "what is faster", this would perform the fastest:
$('#panel p.xyz');
Because it would scope the search to a single element, then find the p
tags, then drop out of the selection all the ones that don't have the proper class.
In some browsers, with a lot of other sibling p
tags that shouldn't match your query, it will perform a lot faster than:
$('#panel .xyz');
Just remember that jQuery uses as many native features as possible. Every single mainstream browser has getElementById
so use an id
where possible.
Next, every browser has a getElementsByTagName
. What some browsers do not have is getElementsByClassName
. So help jQuery help you by using an id
where possible to scope the search, and by pairing tag names with the class for class searches.
Never pass a jQuery object as the scope parameter
One thing you should NEVER do, is your last example:
$(".xyz", $('#panel'));
That would have no speed impact (and in a loop it would be slower) than using a normal string. Only every pass a DOM element into this parameter. This can be very useful when you have the DOM element already:
$("#panel").click(function(){
var p = $("p.xyz", this); // This is fast
});