Micro-optimization in Javascript

07 Feb 2009

Micro-optimization should really be the last thing you worry about when writing Javascript, but I was working on a related project, and this fell out of it:

  • i++,++i are speed-equivalent, and are mostly a style issue for loop counters.
  • i++,++i are about 1.5x faster than i = i + 1 or i += 1
  • JIT makes the differences between all forms vanish
  • Do remember to use var in loop counters (and in general). With out it, loops can be 4x slower.

This is based from 07-Feb-2009 mainline of the Spidermonkey javascript mercurial repository. (This snapshot includes what is known as TraceMonkey.) The results here probably do not apply to other javascript engines, or even future Spidermonkey releases. The differences between i++ and i += 1 are probably a bugfix away from being speed-equivalent ( via bytecode optimization).

The Details

This was tested using a custom C++ application that fires up a javascript context, and directly executes a code snippet. The JIT was explicitly turned on or off. No browser was harmed during these tests. Time is in microseconds.

SnippetNormalJIT
for (var i= 0; i < 10000000; ++i) {}138000039000
for (var i= 0; i < 10000000; i++ ) {}138000039000
for (var i= 0; i < 10000000; i += 1) {}223000040000
for (var i= 0; i < 10000000; i = i + 1) {}2230000 40000
  • ++i, i++ are equivalent, and are mostly a stylistic issue.
  • i +=1, i = i + 1 are equivalent, but 1.6x slower than ++i
  • In this trivial case, the JIT makes the code 30-60x faster.

What happens when you forget to put in the var

SnippetNormalWith JIT
for (i= 0; i < 10000000; ++i) {}427000032000
for (i= 0; i < 10000000; i++ ) {}4240000 32000
for (i= 0; i < 10000000; i += 1) {}680000049000
for (i= 0; i < 10000000; i = i + 1) {}708000049000
j=0;for (i= 0; i <10000000; i = i + 1) {}780000049000


Holy smokes. It makes the code 4x slower. Oddly JIT'ed version actually goes faster, but it's "only" 140x faster than the interpreted version. As for the last entry, I have no idea why another variable added to the script makes it go 10% slower

There you have it. Don't obsess over this too much. It's more interesting than useful.


Comment 2009-05-04 by None

Hmm why does adding a variable slow it down. Hashing? Because of the way "with" works in JavaScript it's very tempting for an implementation to put local variables in an actual hash table. So adding more variables may affect the lookups in that hash table.