JavaScript Selector Performance

JavaScript Selector Performance

After reading a wonderful article by Todd Motto, I further solidified my philosophies of using the HTML5 data-attributes as hooks for JavaScript interactivity, but really wanted to know how JavaScript selector performance impacted such usage.

Years ago, as a young pup on the development scene, I feel victim to jQuery as the new hottness, slathering .css() calls all over my JavaScripts.  As we’ve grown and things like abstraction, code cleanliness and strong separations of content, markup, style and interactivity become more the way of the gun, I still find it odd to use classes and IDs in my HTML markup as hooks for JavaScript.  I’ve also long heard “performance” anecdotes around the differences in IDs and classes in JavaScript.  I must admit, I have only recently gone deep into the world of JavaScript and begun to finally toss jQuery out when I can in preference of raw JS, but I digress.

So if we really want to have true separation between presentation and function, what are we to do?  I know I have found myself writing a decent-sized website with all sorts of great JS and CSS goodness, only to eventually need to change class names or realize I could abstract some CSS into a component or two.  But what’s this?  I just changed a few things around to better compartmentalize my style and now a bunch of my JavaScript is broken.  Crap, I need to go into my app.js and rework all my class selectors.  HTML5 data attributes to the rescue.

You’ve seen them, you’ve used them, something along the lines of

<a href="" data-stuff="cool-thing">Click Me</a>

Those happen to be an excellent candidate for JavaScript hooks.  If you read the article by Todd Motto that I referenced above, he gives a good use-case and explanation of what I’m talking about.  What I wanted to focus on a little bit was performance of these selectors vs class and ID selectors.  I’ve read many comments and smirks saying “that’s what IDs are for, just use IDs, they are faster anyway”.  I’m not so sure about that.

Ok so according to the W3C

“Scripts should refer to an element according to its assigned name. Scripting engines should observe the following precedence rules when identifying an element: a name attribute takes precedence over an id if both are set. Otherwise, one or the other may be used.”

Hmmm, it doesn’t really say anything about class names. Yet it does say that IDs are the lay of the land for the most part. I still find this less than ideal. I feel like IDs are content-explanatory and should be used for identifying sections and pieces of markup and in all reality, I use them specifically for their anchor functionality, especially with all these new-fangled one-pager sites. So when I’m developing a site it just makes a lot more logical sense to me as I’m scanning and writing markup to see data-js or data-hook or data-script to signal “hey this piece of HTML interacts with JavaScript in some way”. I don’t know, call me crazy.

So am I sacrificing performance for “semantics”? Not according to some trials I just did. I ran tests all the 3 selector types in questions, IDs, classes and data-attributes and the results were actually pretty surprising to me. Also, being the closet scientist that I am, I ran a few other tests against jQuery 1.9, the new hottness jQuery 2.0 and just plain old JavaScript. So let’s take a look at what I did.

I basically tried to think of something really simple that I do a lot on sites, the answer in my head was hide/show pieces of content on the page based on an event like on click. So I set up this page and ran tests in the Chrome Dev Tools Timeline section.  I was looking for simple results.  I feel like we over-complicate performance testing sometimes.  The basic gist is, you click a button, how long does it take to “do what it’s supposed to do”.  Well, in this case, you click a button and it fires an event that then “shows” the unordered list of stuff below it.  What’s happening at the most basic level is:

  • Some DOM parsing to get node values
  • Adding a class to an element based on those values
  • A repaint of the browser canvas to display the new DOM and styles associated with the change.

So I am just testing to see how long all this takes.  Here are the full results.  I extrapolated some interesting and not-so-interesting results.  The interesting part was that jQuery 2.0 was actually slower than 1.9.  I just assumed it would be faster since they dropped IE 6/7/8 support, that inevitably means less code and less parsing, so that was kind of neat.  Of course I assumed native JavaScript would be faster and it was, but really not by much.  In all reality we’re talking 1-3 millisecond differences among these results, just by looking at it you can’t tell at all of course, it’s all in the numbers.  Compound those 1-3 milliseconds hundreds of times over and you might have some significant differences.  By that I mean, sure, running this simple test you could easily infer that, it doesn’t matter, just use whatever you want.  But we have to take a lot into account here.  IDs are only used once, that means that first step above is really fast, whereas if you have 20 of the same class selector strewn about your HTML markup (same goes for data-attributes) that first step is inevitably going to be slower.  One of the most surprising results was the fact that the class selector was the fastest method in Native JS and jQuery 1.9 and in fact the slowest in jQuery 2.0.  Yes, jQuery 2.0 is in beta, so we can’t really “use” these results, but it’s still interesting none-the-less.

So What’s my Bottom Line?

1. Don’t use jQuery if you don’t need it.  Too many times have I seen jQuery loaded on a page (ahem, WordPress developers) and never really used.  It might be accessed once for sizzle.js, the JavaScript selector library portion of jQuery.  Don’t load jQuery just to do something like


That’s just silly. Just use JavaScript, check the source on my js-raw test.  If you’re doing a lot of DOM manipulation and AJAX requests and JSON fetching, then yeah, it’s cool, that’s what jQuery is for, just don’t use it as a crutch.  Also, learn what jQuery is actually doing, read the source and watch Mr. Paul Irish walk through some of it.

2. For all intents and purposes, the pros outweigh the cons in my mind whether to use data-attributes as hooks vs IDs.  Use the data-attributes, it will make more sense in your markup and will keep you from having to touch your JavaScript at all if presentation (style) should need to change.

3. I definitely don’t think we should be using class selectors (even if they are faster).

I would love to hear comments about this, some people get really passionate about this stuff and I’d love to hear about other tests, pitfalls, drawbacks, etc.  Maybe once you start compounding tons of data-attr selectors something weird happens that I’ve never encountered, I want to hear about those kinds of scenarios.

48 Responses to JavaScript Selector Performance says: November 6, 2013 at 1:05 am

Hi there, just become alert to your weblog thru Google, and found that it’s truly informative. I am gonna be careful for brussels. I will be grateful for those who proceed this in future. A lot of other folks can be benefited out of your writing. Cheers!

driveway gates says: November 7, 2013 at 6:20 pm

Pretty component of content. I simply stumbled
upon your web site and in accession capital to claim that I acquire
actually loved account your blog posts. Any way I’ll be subscribing
for your feeds and even I achievement you access constantly

Ioanna says: March 15, 2014 at 8:42 pm

What i don’t realize is in fact how you’re no lneogr actually much more smartly-liked thanyou’ll be right now. You are very intelligent. You understand thus significantly on the subject of this matter, produced me for my part imagine it from so lots of a range of angles. Its like men and women are not involved unless its something to do with Lady gaga! Your personal stuffs nice. Always maintain it up!

Leidy says: March 16, 2014 at 2:54 am

What i don’t realize is in fact how you’re no loengr actually much more smartly-liked thanyou’ll be right now. You are very intelligent. You understand thus significantly on the subject of this matter, produced me for my part imagine it from so lots of a range of angles. Its like men and women are not involved unless its something to do with Lady gaga! Your personal stuffs nice. Always maintain it up!

Henrietta says: June 3, 2014 at 7:15 am

Useful info. Lucky me I discovered your website accidentally, and I am shocked why this coincidence did not took place
in advance! I bookmarked it.

Here is my web page: yamaha boats for sale in texas (Henrietta)

Tayla says: July 11, 2014 at 4:24 am

excellent points altogether, you simply won a
emblem new reader. What could you recommend about your put up
that you simply made some days ago? Any positive?

Review my web-site – roofing contractor hinsdale (Tayla)

Angelita says: October 3, 2014 at 9:43 am

wonderful submit, very informative. I’m wondering why the opposite experts of this sector don’t understand this.
You must proceed your writing. I’m confident, you’ve
a great readers’ base already!

my homepage translate online (Angelita)

extended file says: January 16, 2015 at 11:20 pm

My brother suggested I may like this blog.
He used to be totally right. This submit actually made my day.
You can not consider just how a lot time I had spent for this info!
Thank you!

Arianne says: January 22, 2015 at 2:35 am

When I initially left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and from
now on every time a comment is added I receive 4 emails with
the exact same comment. Is there a way you can remove me from that service?

Pahlawan says: February 21, 2015 at 11:29 am

This is really a good idea! I was woredning why Ahana was eating Bananas and declaring them as healthy! Now I know the reason !! Please have more of these to reinforce the shift towards healthy eating Best wishes-Kasturi

Stephaine says: February 22, 2015 at 11:59 pm

whoah this weblog is great i really like studying
your posts. Keep up the great work! Yoou understand, many persons are
searching round for this info, youu couuld
help them greatly.

panties says: March 1, 2015 at 7:42 am

This means that a church or girl scouts group could have their website on the same server and IP address as
a porn site therefore end up blocked. He told
me everyone else made money off his brother.
I’m not a historian or any sort of cultural expert, but I do live in China,
and I do see some similarities in the way the Chinese government works and the thought process of the people here.

mobil porno says: March 2, 2015 at 11:03 am

Thanks for your personal marvelous posting!
I definitely enjoyed reading it, you are a great author.

I will be sure to bookmark your blog and may come back
very soon. I want to encourage you to continue your
great job, have a nice morning!

Steve says: March 4, 2015 at 11:45 pm

I’m amazed, I have to admit. Rarely do I come across a blog that’s both equally educative and interesting, and let me tell you, you have hit the nail on the head.
The issue is something too few folks are speaking intelligently about.
Now i’m very happy I came across this during my search for something relating to this.

Reply says: March 17, 2015 at 7:42 am

When there is nonstop noise in your ears, normal functions of
life become burdens. You can’t cure tinnitus before you know what has started it.

The Tinnitus Miracle is accessible in PDF format and can be downloaded on both pc and on your Mac.

Here is my web site … psoriasis on penis – -

Yasmin says: March 19, 2015 at 8:58 pm

Though Indian outsourcing providers are cheaper compared to their global counterparts, difference exists
amongst various Indian providers. Information has to be clearly presented and grammatically correct.
300 senior executives from Fortune 1000 companies were interviewed for the

Jual Knalpot ninja 250 rr mono says: March 30, 2015 at 10:06 am

At everyone else’s loss you can pick up a brand new 2009 or 2010 Versys
at your local dealership for a steal and enjoy function over form.
The connecting rods havee been shortened slightly in the 300 engine,
increasing the stroke frm 41. Beginning by cutting
the litrle bits that stick out from the damage
till the edges are smooth.

Vita youth Serum says: April 13, 2015 at 3:09 am

What i don’t understood is if truth be told how you’re now not
actually a lot more neatly-appreciated than you may be right
now. You’re very intelligent. You understand thus significantly relating to this subject, made me for my
part believe it from a lot of numerous angles.
Its like women and men don’t seem to be fascinated except it’s something to do with Girl gaga!
Your individual stuffs nice. Always handle it up!

slim extreme skincare says: April 25, 2015 at 1:43 pm

Thanks , I have recently been searching for info approximately
this subject for a long time and yours is the greatest I have found out so far.
But, what concerning the conclusion? Are
you positive about the source?

Testostorm Supplement says: June 20, 2015 at 5:50 am

I’m impressed, I have to admit. Rarely do I encounter a blog
that’s both equally educative and engaging, and let me tell you, you’ve hit the nail on the head.
The problem is an issue that too few folks are speaking intelligently about.

Now i’m very happy I came across this in my search for something regarding

Nature Cleanse Renew says: June 23, 2015 at 1:24 pm

I was extremely pleased to discover this page.
I want to to thank you for your time for this particularly wonderful read!!

I definitely really liked every part of it and i also have
you book marked to look at new information on your site.

Reply says: July 2, 2015 at 12:40 pm

ve been taking the drug within a few days of the drug test, marijuana could still be detected in a
urine test up to a month after the last time it
is used. Some of the toted methods of curing the chigger bite is simply household
bleach, such as Clorox. Neutral p – H products are safer for the environment and end user.


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>