Basically, is
$("#someid")
or
$(".someclass")
faster than
$("[someattr='value']")
I would imagine that it is (that is, selection by id is fastest, then class, then attribute), but does anyone know for sure?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
ID is absolutely the fastest. Part of the reason is that ID is supposed to be unique, so the API stops searching after the ID is found in the DOM.
If you must use a class or attribute selector, you can improve performance by specifying the optional context parameter.
For example…
Where
somecontaineris something like a div, surrounding an element with classsomeclass. This can offer a huge performance benefit in the cases wheresomecontainercomprises a small fraction of the DOM.UPDATE:
I did some tests a couple years ago around the context parameter. After reading the comments below I was curious if anything has changed. Indeed, it seems the scene has changed somewhat with today’s browsers. Maybe it also has to do with improvements in jQuery? I don’t know.
Here are my results with 10,000 iterations (code is below):
IE9
$(".someclass")– 2793 ms$(".someclass", "#somecontainer")– 1481 msChrome 12
$(".someclass")– 75 ms$(".someclass", "#somecontainer")– 104 msFirefox 3.6
$(".someclass")– 308 ms$(".someclass", "#somecontainer")– 357 msSo among these big 3 modern browsers, the context parameter only seems to help IE9. Older browsers will also benefit from the context parameter. But considering the prevalence of each of these browsers and averaging everything out, the net gain is somewhat of a wash now.
And here’s the code in case anyone wants to try it themselves…