Tuning JavaScript code

One of the things I really love is to optimize code. Today I did some profiling using Firebug, and I saw that two methods were called a lot:
  • AJS.map (about 1500 calls)
  • AJS.createDom (about 300 calls)

I improved AJS.createDom by doing following tweaks:

  • Removed method lookups (AJS.isNumber and AJS.isString)
  • Added a local variable deceleration using var
  • Rewrote AJS.map to a for loop

These updates did give a performance boost, from 55ms to 40 ms - a "whooping" 15ms :D

I looked in AJS.map and I saw this call:

fn.apply(null, [list[i], i])

This is expensive! So I rewrote it to:

fn(list[i], i)

And bam, this gave a 2x speed improvement (from 30ms to 15 ms).

Two tips on JS optimization

Always use the var deceleration for local variables. Why? It tells JavaScript that the variable is local, i.e. JavaScript won't look for the variable in the outside scope.

Always use local decelerations for lookups that you use multiple times. Why? JavaScript code isn't optimized, so lookups wont be cached.

Benchmarks · Code · Code improvement · JavaScript 8. May 2007
© Amir Salihefendic. Powered by Skeletonz.