Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 441
si618 Avatar asked Feb 18 '10 05:02

si618


1 Answers

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() { //...
like image 170
Christian C. Salvadó Avatar answered Oct 18 '22 13:10

Christian C. Salvadó