Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 956
Haroldo Avatar asked Apr 06 '10 08:04

Haroldo


3 Answers

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")
like image 112
3 revs Avatar answered Nov 14 '22 22:11

3 revs


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).

like image 28
Eric Avatar answered Nov 14 '22 22:11

Eric


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.

like image 41
jAndy Avatar answered Nov 14 '22 23:11

jAndy