views:

109

answers:

2

Has anybody bench marked selecting elements with id's and class's from CSS and javascript?

It would make sense that an element with an id is faster to select than if it had a class even if it was the only element with that class.

Do I really need to be concerned?

+4  A: 

I don't think you should be really that concerned : selecting by id and selection by class just don't have the same meaning :

  • If you want to select an element, knowing how to uniquely identify it, use it's id
  • If you want to select one or many elements, knowing there might be more than one, note having a way to uniquely identify it/them, use the class.


Still, here's a benchmark that could interest you : Speed/validity selectors test for frameworks.

Pascal MARTIN
Thanks for the link - It may take sometime to digest the data! I tend to overuse the 'class' which works for me, hence the question.
zaf
+1 for the link
pixeltocode
+3  A: 

When searching for an id, the selector will halt as soon as it's found a match (even if there are many) - I assume there's some sort of key/value lookup table for this purpose, as it's much faster than DOM traversal. Here's why, and here's an excerpt:

It's still much better to select by ID...because jQuery uses the browser's native method (getElementByID) to do this and doesn't have to do any of it's own DOM traversal, which is much faster.

The linked results there show >100x speed improvement with id vs class.

When searching for a class, the entire DOM (or scope) is searched. Here's a benchmark using scope.

You can benchmark selectors in your own browser here.

Andy
Can you back that up with a reference?
zaf
The whole DOM is searched even if `:first` is used as a selector? >.<
Matt
@Matt that's jquery, not javascript ;)
Andy
@zaf try it - put multiple IDs on a page and test the output, you'll only get one. I'll find you a reference too!
Andy
Strangely, using BBC's homepage as a testing ground (massive DOM), I selected the element(s) with classes `.hpMod.altcolour2.hpCo` 1000 times, and it took 223ms. I did it again, but with `first` added, and it took 323ms >.<. document.getElementById("i), which was the element I robbed the classes off, took 1ms overall; selecting the element 1000 times.
Matt
@Andy: Damn, as soon as I hear selectors these days, I'm already loading up http://api.jquery.com/category/selectors ;)
Matt
@Matt I had to re-read the question :) interesting about :first there, using jquery 1.4.2?
Andy
@Andy: Yes [4.3.2.1.]
Matt
+1 for the links
pixeltocode