Optimizing Javascript

This article is about optimizing JavaScript, specifically for the Spider Monkey engine used by Konfabulator.

Math.log
Problem: log(a/b) is equivalent to log(a) - log(b), but which one executes faster?

Conclusion: log is slower than division, so use log(a/b). function go{ var n = 1000000; var dummy, i; var start,end;

start = new Date; i = n; while(--i){ dummy = Math.log(n) - Math.log(i); } end = new Date; print("go",end-start); // gave me 2953 msecs

start = new Date; i = n; while(--i){ dummy = Math.log(n/i); } end = new Date; print("go",end-start); // gave me 1985 msecs }

Arrays: push vs unshift
If you're adding elements to an array, you can either new entries to either the beginning with unshift, or to the end with push. push is significantly faster than unshift.

Loops

 * Optimizing JavaScript for Execution Speed Also check out the links on page 5.