Archive for the ‘Optimization’ Category

Javascript optimization guidelines

Monday, May 19th, 2008

The Opera dev guys have put together a great list of JS optimization primers. Most of them I already follow, but a few of them were pleasant surprises.

The ones I already follow and which require little or no explanation or justification are:

  • Avoid using global variables
  • Avoid for-in in performance-critical functions
  • Pass functions, not strings, to setTimeout() and setInterval()
  • Isolate uses of eval and with
  • Don’t use try-catch-finally inside performance-critical functions
  • Avoid using with
  • Avoid using eval or the Function constructor
But these were the gems:
String Value to Object conversion when calling methods
The difference between 

var s1 = '0123456789';


var s2 = new String('0123456789');

is that s2 is an object with a bunch of associated methods, e.g. charAt and split, while s1 is just a value without these methods. When you call a string method on a string value, e.g. s1, the runtime engine has to convert that value into a temporary string object, call that method, return the value, and then discard the temporary object.
Who would have thought?
String concatenation
Similarly, the difference between

a1 += 'x' + 'y';


a2 += 'x';
a2 += 'y';

is that the concatenation of a1 requires a temporary variable to store ‘xy’ in before this gets appended to a1. That extra memory and garbage collection cycles is saved in the creation of a2.
Primitive operators can be faster than method calls
If you really need the very last ounce of performance, instead of writing

var min = Math.min(a,b);

use the slightly less convenient but faster

var min = a < b ? a : b;
A[A.length] = v;

This one certainly makes sense - but as always: first get it right by using whatever means you feel most comfortable with. Then if you really need it, get primitive.