Haroldo
Haroldo

Reputation: 37377

jQuery selectors: $('#ID1, #ID2, #ID3') vs $('1X CLASS') which is faster?

Looking into selector performance between $('#ID1, #ID2, #ID3') vs $('1X CLASS'). Which is faster?

Upvotes: 6

Views: 4731

Answers (6)

jAndy
jAndy

Reputation: 235992

In general, searching for id's is done by getElementbyId, which is the fastest possible way to select a DOM element. If available, getElementByClass is used to grab a node by class name.

Again, getElementById is the fastest way. Performing getElementById three times against one getElementByClass needs some benchmarking to find out the speed difference.

But if the browser does not support getElementByClass, it's even more slow.

Upvotes: 3

Anurag
Anurag

Reputation: 141879

Looks like .class is working faster for this case. jQuery might not be going the getElementById route. Chrome and Safari are probably being optimizing with getElementsByClassName.

Tests @ http://jsfiddle.net/mGqyH/4/

Chrome

Chrome http://img339.imageshack.us/img339/5021/chromew.png


Safari

alt text http://img339.imageshack.us/img339/5021/chromew.png


Firefox

Firefox performance http://img94.imageshack.us/img94/1123/firefoxg.png


Document used (modified)

http://www.w3.org/TR/DOM-Level-2-Events/events.html

combined IDs selector

$("#Events, #table-of-contents, #Events-overview, #Events-flow-capture, #Events-EventTarget, #Events-EventListener")

disjoint IDs selector

$("#Events").add("#table-of-contents").add("#Events-overview").add("#Events-flow-capture").add("#Events-EventTarget").add("#Events-EventListener");

class selector

$(".selectMe")

Upvotes: 7

Peeter
Peeter

Reputation: 9382

Updated http://jsfiddle.net/uD7Qz/1/ with .add method.

.add method is almost as fast as $(.class), on Chrome. On FireFox it's 4x slower then $("#1, #2, #4").

Atleast those were my results.

Upvotes: 2

Pawan Mishra
Pawan Mishra

Reputation: 7268

jQuery selectors work on same principle as that of CSS selectors(generalized statement not an exact fact).And in CSS , id selector are more faster when compared to that of class selector.So $("#myDiv") is more faster than #(".myDivClass").

Upvotes: 0

Eric
Eric

Reputation: 97571

Use this instead, if you want performance:

$("#id1").add("#id2").add("#id3")

There's less string parsing to do here. That should be faster than selecting by class name, unless the browser has a native implementation (some do).

Upvotes: 4

Matt Lohkamp
Matt Lohkamp

Reputation: 2192

Just as a guess, I'd say selecting by ID is faster, since document.getElementByID() is a built-in function to javascript, while 'getElementByClass()' is something that various custom functions have been built to solve. Ideally too, looking for $('div#id') is going to be faster because it's more specific and allows the search loop to cut out certain paths that have no chance of coming back positive.

Upvotes: 1

Related Questions