views:

127

answers:

1

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 approximately 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?

+9  A: 

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() { //...
CMS
great explanation.
Rakesh Juyal
Thanks @Rakesh!
CMS
Thanks. So does each attribute selector iterate over the DOM separately? Or does it iterate just once, but evaluation of attributes is faster because it only has to check for id (short-circuited?) instead of multiple attributes?
Si
You could do... $('#' + code).each(function(){});Here is a good link to JQuery Selector Performance Rules. http://www.artzstudio.com/2009/04/jquery-performance-rules/
delux247
@delux, thanks for the link, and note operator is $= so #+code won't work.
Si