开发者

Why is this jQuery selector so slow?

Based on testing a page with ~220 elements, of which ~200 are checkbox elements, and each element has to query an array with ~200 items, I was surprised to discover that input selector:

$("input[id$='" + code + "']").each(function() { //...

is approximately 4-5 times faster than

$("input:checkbox[id$='" + code + "']").each(function() { //...

and approx开发者_Python百科imately 10 times faster than a checkbox selector:

$(":checkbox[id$='" + code + "']").each(function() { //...

Also tried universal selector *, which performed about the same as input.

I'm curious to understand why such a big difference in performance?


Your first example is the faster because it only involves the check of the id attribute, on all the input elements.

The input:checkbox selector is equivalent to an Attribute Equals selector:

$('input[type=checkbox]')

So basically you are doing two attribute selectors in your second example:

$("input[type=checkbox][id$='" + code + "']").each(function() { //...

Now in your third example, since you don't specify a tag name or anything else, it will inspect all DOM elements, since the :checkbox selector is equivalent to :

$("*:checkbox")//...

That's why is always recommended to precede this kind of selectors with a tag name or some other selector.

At the end, your third example (the slowest) is equivalent to something like this:

$("[type=checkbox][id$='" + code + "']").each(function() { //...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜