Perf Test your jQuery Selectors using jsPerf
Posted by: Suprotim Agarwal
in Category jQuery and ASP.NET
Abstract: Performance Test your jQuery Selectors using the jsPerf online tool.
We will demonstrate one such technique that says you should never prepend a tag name before an ID as it slows down the selector. So essentially that means if you have a DIV element with an id description, do not use div#description to select the element. Instead use only #description which is better performing than the latter. But how do we test this theory? Let’s use jsPerf.
Go to jsperf and set up some basic info for your test case. I have set it up over here http://jsperf.com/prepend-tag-before-id. Start by mentioning a Title and Description of our test case
Scroll down to write some preparation code which is essentially some HTML code on which our selectors will work
The next step is to write some code snippets to compare. We are essentially comparing two pieces of code:
$('div#description').css('border', '1px solid #000000');
$('#description').css('border', '1px solid #000000');
Where in the first snippet we are prepending the Div tag before ID (div#elementid) VS selecting the element directly by its ID (#elementid)
Scroll down to the bottom and click on ‘Save Test Case’. In our case, the jsperf test got saved as http://jsperf.com/prepend-tag-before-id
Run the tests and see which code performs better. Here’s a test run on Chrome v32.0
..and here’s a test run on IE 11.0
jsperf keeps a track of each browser result, so you can compare benchmark tests across environments. Here’s a snapshot of the same test run in different browsers and the performance comparison across browsers.
As you can see, after running some tests on jsperf.com, we can see that the snippet which does not prepend tag before ID (shown in red) performs better than the snippet which prepends tag before ID (show in blue). The higher the number, the better it is as it conveys a higher number of operations per second. Hence using this simple jsperf test, we can reach the conclusion that if you prepend the tag name before an ID, it slows down the selector.
As Developers, should our focus be Code Readability or Performance?
This question lingers the mind of most developers out there. One point to always remember and as quoted by Donald Knuth is Premature optimization is the root of all evil (or at least most of it) in programming. Your focus should be on writing the correct algorithm. Write it in a way that’s correct and readable. Don’t spend too much time on optimization unless you exactly know what to optimize.
I introduced you to jsPerf.com so that you are aware of a tool that can help you test your code snippets when you have empirical evidence that your code is not performing well. Use it meticulously!
This article was taken from my upcoming The Absolutely Awesome jQuery Cookbook at www.jquerycookbook.com