Thomas Fuchs
Hi, I'm Thomas Fuchs. I'm the author of Zepto.js, of, and I'm a Ruby on Rails core alumnus. With Amy Hoy I'm building cheerful software, like Freckle Time Tracking and Every Time Zone and write books like
   Want me to speak at your conference? Contact me!

JavaScript snippets performance

August 14th, 2010

When working on performance optimization fine-tuning, it’s great to have some help in the form of benchmarks of various strategies to achieve your code goals. Mathias Bynens has come up with a slick site to do just that, meet jsPerf!

First take a look at the various test cases that are already in there.

Here’s a test case I wrote out of interest comparing various strategies to test if a given property exists in an object (view it on jsPerf):

// for a given object
var obj = {
   a: 1

// test which is fastest
// variant 1: in operator
if ('a' in obj) {};
if ('b' in obj) {};

// variant 2: boolean value (might yield wrong results with certain values!)
if (obj.a) {};
if (obj.b) {};

// variant 3: hasOwnProperty
if (obj.hasOwnProperty('a')) {};
if (obj.hasOwnProperty('b')) {};

Perhaps not surprisingly, variant 2 is fastest (at least on Safari 5.0.1). Note that this particular way to test for properties might yield wrong results (a property with a value of false wouldn’t be detected, for example).

JsPerf is double-awesome! While it is of course great to test the performance of code, most importantly your findings are shared with other developers (and they can suggest new solutions!). Be sure to browse through the test cases—a great way to learn about alternative ways to code JavaScript.