How to Make Your JavaScript Fast

Mozilla's David Mandelin has published an interesting slideshow about JS optimization. Here are the takeaway points in case it disappears. The takeaway points:

Treat variables as if they were strongly typed

E.g., if var a=1 don't assign a string to a later on

Use objects of the same 'shape'


var obj1 = { a:1, b:2, c:3 };
var obj2 = { a:2, b:78, c:19 };
var obj3 = { a:5, d:"oh noes" };

obj1 and obj2 have the same shape, obj3 doesn't.

Prototype chain

The prototype chain is preferable to deeply nested closures, because the steps to fetch variables are cached with prototype chains, whereas they are not with closures

Short lived objects

Make objects short lived, and don't create new objects at too high a rate


Use densely packed arrays


for loops are the fastest; .map / .reduce slower; for in the slowest; call / apply are also slow, as is accessing arguments

Don't try too hard

try / catch / finally is actually slow