For example, let’s say we we want to compare the following blocks of code:
Some code before refactoring:
Some code after refactoring:
The second snippet should be faster, because we cache the paragraph.length and node lookups, and use the native DOM interface for accessing style / class data. But how much faster? jsPerf can tell us.
##Setting up a jsPerf test
The procedure is pretty simple:
- You enter a name for your test
- You can specify some setup / teardown JS for each test (the time to run this will be excluded from the recorded time for each test)
- You add however many snippets you want to compare
- You save the test (which gives you a shareable URL - this is important)
Let’s see the results (http://jsperf.com/rm-demo):
Pretty dramatic. But what if I want to test in other browsers? I can revisit the page in another browser, run the test again, and – this is the best thing – compare results between browsers, which are saved every time. For example, let’s run this test again in IE7:
Much slower, but we can see the optimization isn’t browser specific. And we can see that with a browser as slow as IE7, this is probably an optimization worth using again in future.
Obviously, we shouldn’t be in the business of optimizing our code prematurely, but if you’re doing something performance critical (animation or manipulating a really large DOM), jsPerf can be a really handy tool for answering those tricky questions and giving you some hard numbers. Definitely worth a bookmark.