jQuery class selector performance (confused)
So is $('table.selectable td.capable input:text')
preferable to $('table.selectable td input:text')
? In other words, does specifying a class speed up o开发者_Go百科r slow down the selection (assuming it isn't absolutely required in this scenario)?
I did not check the Sizzle implementation, but in the best case, td
would map to something like getElementsByTagName() and .capable
to something like getElementsByClassName(), if available. So both would be comparable in terms of speed.
However, there is no getElementsByTagNameAndClassName()
method as far as I know, so resolving td.capable
probably requires an additional filtering pass after the DOM call. So, I'm quite inclined to think it would be slower.
Naturally, a benchmark would tell for sure.
So I did some benchmarking with firebug, and in the particular example I listed in the question, the latter (without the td class specifier) is faster.
Depends on the context.
Generally, the more sub-checks that need to be made, the slower it will be, as each takes time. The point is, they are obviously not necessarily the same results. One is a sub-set of the other.
For the most part, aim to have the minimal number of selectors required to target the specific set you require. Also bare in mind that some selectors perform far better (due to browser method availability) than others. ID selectors #id
and in modern browsers tag selectors, are far quicker than class searches .class
, which require iterative string analysis of the .className
parameter, or indeed attribute based searching, which is much the same usually.
If in doubt, perform metrics.
精彩评论