Just after writing about selecting elements by data- attributes, I discovered Roy’s post about this subject and his (positive!) performance measurements. Although I honesly thought it would be slower but he concludes that selecting by data attributes is actually not significantly slower than selecting by classname (<10% difference most of the time). The only exception is IE being 50-70% slower.

So that’s good news!

And I understand Roy’s motivation for coming up with the numbers: a lot of folks seems to reject the idea because they think that:

their DOM queries will be much slower slower DOM queries will make their website/application slower.

So while Roy has mostly debunked #1, let me show you #2 doesn’t hold up either, if you follow these principles (and you should!).

Cache your queries

All methods to find elements in the DOM take time. A lot of time compared to just executing a single javascript statement. So always cache the elements you’ve already selected and re-use them! In fact this is my dearest rule about programming with jQuery because not only does it increase performance, it also keeps the code DRY and helps you catch typos earlier.

Scope your queries

Secondly, scanning the whole document if you don’t have to is a waste. If you have something like a dialog then first select the dialog’s root element and then, when selecting anything inside the dialog, like a button, use a scoped query, like this:

var $dialog = $("[data-role='dialog']"); var $button = $dialog.find("[data-role='button-ok']");

Don’t use script to apply style

Lastly, script is mostly dormant after the initial loading of the page. It normally takes user interaction for script to become alive. This means nobody is noticing a 25ms delay before the event handlers are attached! But, if you use script to apply styling of a component at page load then not even selecting by id will prevent a FOUC. Therefore, always serve out the html with the correct styling initially.

No more excuses!

Stick to these principles and selector performance will mostly be a non-issue. Chances are you were doing it already to keep your code clean and DRY. So what’s the excuse? Go ahead and use data attributes for selecting elements! You might like it ;-)

This is a follow-up to my post classnames for styling, data attributes for behavior

Discuss on reddit/r/javascript