FANDOM


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

Math.log Edit

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() Edit

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 Edit