Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method for testing DOM selector efficiency

Is there any straightforward way to evaluate DOM selector efficiency on a page? My curiosity comes from a page written with jQuery, but ideally I'm looking for something more generic (I appreciate the efficiency of selector may differ between approach used to locate it).

This came from a situation where I had a form, say #myForm which contained a <button class="button">

As a selector I was using #myForm button, but I could obviously use #myForm .button , #myForm button.button and a few other alternatives.

Whilst in this example the different is trivial, I wondered whether there is a general consensus as to best approach and further to that, whether there is an easy way to pop together a test page of sorts to experiment with combinations. This then made my realise I have not a clue how to performance test a selector, does anyone have any preferred routes to perform this type of action? Any thoughts appreciated.

like image 216
dougajmcdonald Avatar asked Jul 14 '26 14:07

dougajmcdonald


1 Answers

The order of dom selectors according to this article: http://csswizardry.com/2011/09/writing-efficient-css-selectors/

  • ID, e.g. #header
  • Class, e.g. .promo
  • Type, e.g. div
  • Adjacent sibling, e.g. h2 + p
  • Child, e.g. li > ul
  • Descendant, e.g. ul a
  • Universal, i.e. *
  • Attribute, e.g. [type="text"]
  • Pseudo-classes/-elements, e.g. a:hover

I've created a jsperf text with some example selectors to show how you can test each one: http://jsperf.com/dom-selector-testing

From those results the fastest to the slowest is:

  • getElementById
  • getElementsByTagName
  • getElementsByClassName // ie8 does not support this
  • querySelector
like image 165
Kim T Avatar answered Jul 16 '26 04:07

Kim T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!