Scaling back on jQuery and other JavaScript libraries
I'm observing a trend in blogs and presentations: scale back on libraries like jQuery.
In his popular presentation called "Enough With The JavaScript Already!," Nicolas Zakas points out that JavaScript is bloating our bandwidth, and we're not even using it all. Evan Hahn reminds us of some of jQuery's equivalent native DOM methods. Chris Love gently states, "In many ways thanks to jQuery, jQuery itself is no longer needed."
I was curious about how jQuery and Zepto stack up against native DOM methods. Obviously, the native methods will perform better, but I was surprised at how much better. In full front-end applications like my own website, this can actually make a difference.
First I tested fetching an element by ID:
getElementById() | querySelect() | $("#") | Zepto $("#") | |
---|---|---|---|---|
Chrome | 6ms | 35ms | 110ms | 167ms |
Firefox | 13ms | 90ms | 505ms | 297ms |
Safari | 17ms | 176ms | 310ms | 945ms |
IE9 | 47ms | 2745ms | 177ms | × |
IE10 | 55ms | 4023ms | 132ms | × |
Then I tested fetching elements by class name (I didn't test Zepto in IE here):
getElementByClassName() | querySelectAll() | $(".") | Zepto $(".") | |
---|---|---|---|---|
Chrome | 7ms | 1515ms | 169ms | 377ms |
Firefox | 18ms | 1857ms | 802ms | 475ms |
Safari | 19ms | 1451ms | 920ms | 993ms |
IE9 | 96ms | 4142ms | 423ms | × |
IE10 | 68ms | 4029ms | 309ms | × |
I was surprised to see how badly the native document.querySelect()
and document.querySelectAll()
methods faired. I'd expect performance for these to improve over time though.
It's unclear why Zepto was so much slower for some tests. I expected it to do better than jQuery. I'll have to dig into this one.
How did I measure performance?
I used a very basic approach, executing each selector 10,000 times and taking advantage of the built-in console.time
and console.timeEnd
methods (I had to measure time manually for IE):
I can't imagine giving up jQuery just yet, but I would love to, for now, just use the Ajax and CSS APIs. And I'd also like to see Ember use native selectors more frequently.