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="http://awesomesite.com" 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

$("#some-id").hide();

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.

13 Responses to JavaScript Selector Performance

www.googl.com 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!

Reply
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
quickly.

Reply
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!

Reply
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!

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

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

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

Reply

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>