jQuery class selector performance (confused)

2019-04-05 17:47发布

问题:

So is $('table.selectable td.capable input:text') preferable to $('table.selectable td input:text')? In other words, does specifying a class speed up or slow down the selection (assuming it isn't absolutely required in this scenario)?

回答1:

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.



回答2:

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.



回答3:

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.