Javascript – why is the latter function 10% faster although it must create the variables over and over again

javascriptperformance

var toSizeString = (function() {

 var KB = 1024.0,
     MB = 1024 * KB,
     GB = 1024 * MB;

  return function(size) {
    var gbSize = size / GB,
        gbMod  = size % GB,
        mbSize = gbMod / MB,
        mbMod  = gbMod % MB,
        kbSize = mbMod / KB;

    if (Math.floor(gbSize)) {
      return gbSize.toFixed(1) + 'GB';
    } else if (Math.floor(mbSize)) {
      return mbSize.toFixed(1) + 'MB';
    } else if (Math.floor(kbSize)) {
      return kbSize.toFixed(1) + 'KB';
    } else {
      return size + 'B';
    }
  };
})();

And the faster function:(note that it must always compute the same variables kb/mb/gb over and over again). Where does it gain performance?

function toSizeString (size) {

 var KB = 1024.0,
     MB = 1024 * KB,
     GB = 1024 * MB;

 var gbSize = size / GB,
     gbMod  = size % GB,
     mbSize = gbMod / MB,
     mbMod  = gbMod % MB,
     kbSize = mbMod / KB;

 if (Math.floor(gbSize)) {
      return gbSize.toFixed(1) + 'GB';
 } else if (Math.floor(mbSize)) {
      return mbSize.toFixed(1) + 'MB';
 } else if (Math.floor(kbSize)) {
      return kbSize.toFixed(1) + 'KB';
 } else {
      return size + 'B';
 }
};

Best Answer

Modern JavaScript engines all do just-in-time compilation. You can't make any presumptions about what it "must create over and over again." That sort of calculation is relatively easy to optimize out, in either case.

On the other hand, closing over constant variables is not a typical case you would target JIT compilation for. You typically create a closure when you want to be able to change those variables on different invocations. You're also creating an additional pointer dereference to access those variables, like the difference between accessing a member variable and a local int in OOP.

This sort of situation is why people throw out the "premature optimization" line. The easy optimizations are already done by the compiler.

Related Topic