14
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';
 }
};
8
  • 3
    In any statically typed language the "variables" would be compiled as constants. Maybe modern JS engines are capable of doing the same optimization. This seems not to work if the variables are part of a closure.
    – usr
    Mar 15, 2015 at 13:31
  • 6
    this is an implementation detail of the JavaScript engine you're using. The theoretical time and space are the same, it's only the implementation of a given JavaScript engine that will vary these. So to answer your question correctly, you need to list the specific JavaScript engine you measured these with. Perhaps someone knows the details of it's implementation to say how/why it made one more optimal than the other. Also you should post your measurement code. Mar 15, 2015 at 14:46
  • you use the word "compute" in reference to constant values; there's really nothing to compute there in what you're referencing. Arithmetic of constant values is one of the most simple and obvious optimizations compilers do, so anytime you see an expression that only has constant values, you can just assume the whole expression is optimized to a single constant value. Mar 15, 2015 at 15:05
  • @JimmyHoffa thats true, but on the other hand it needs to create 3 constant variables every function call...
    – Tomy
    Mar 15, 2015 at 15:09
  • @Tomy constants aren't variables. They don't vary, thus they don't need to be recreated after compilation. A constant is generally placed in memory, and every future reach for that constant is directed to the exact same place, there's no need to recreate it because it's value will never vary, therefore it is not a variable. Compilers generally will not emit code that creates constants, the compiler does the creation and it directs all code references to what it made. Mar 15, 2015 at 15:10

3 Answers 3

24

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.

2
  • I suspect it's that scope traversal for variable resolution that's causing the loss as you mention. Seems reasonable, but who truly knows what madness lies in a JavaScript JIT engine... Mar 15, 2015 at 15:02
  • 1
    Possible expansion of this answer: the reason a JIT would ignore an optimization that's easy for an offline compiler is because performance of the whole compiler is more important than of unusual cases. Mar 15, 2015 at 20:23
12

Variables are cheap. Execution contexts and scope chains are expensive.

There are various answers that essentially boil down to "because closures", and those are essentially true, but the problem isn't specifically with the closure, it's the fact that you have a function referencing variables in a different scope. You'd have the same problem if these were global variables on the window object, as opposed to local variables inside the IIFE. Try it and see.

So in your first function, when the engine sees this statement:

var gbSize = size / GB;

It has to take the following steps:

  1. Search for a variable size in the current scope. (Found it.)
  2. Search for a variable GB in the current scope. (Not found.)
  3. Search for a variable GB in the parent scope. (Found it.)
  4. Do the calculation and assign to gbSize.

Step 3 is considerably more expensive than just allocating a variable. Moreover, you do this five times, including twice for both GB and MB. I suspect that if you aliased these at the beginning of the function (e.g. var gb = GB) and referenced the alias instead, it would actually produce a small speedup, although it's also possible that some JS engines already perform this optimization. And of course, the most effective way to speed up execution is simply not to traverse the scope chain at all.

Keep in mind that JavaScript is not like a compiled, statically-typed language where the compiler resolves these variable addresses at compile time. The JS engine has to resolve them by name, and these lookups happen at runtime, every time. So you want to avoid them when possible.

Variable assignment is extremely cheap in JavaScript. It might actually be the cheapest operation, although I have nothing to back up that statement. Nonetheless, it's safe to say that it's almost never a good idea to try to avoid creating variables; almost any optimization you try to do in that area is actually going to end up making things worse, performance-wise.

4
  • And even if the "optimization" doesn't affect performance negatively, it almost certainly is going to affect code readability negatively. Which, unless you're doing some crazy computational stuff, is most often a bad tradeoff to make (apparently no permalink anchor unfortunately; search for "2009-02-17 11:41"). As the summary there goes: "Choose clarity over speed, if speed is not absolutely needed."
    – user
    Mar 15, 2015 at 21:37
  • Even when writing a very basic interpreter for dynamic languages, variable access during runtime tends to be an O(1) operation, and O(n) scope traversal is not even needed during initial compilation. In each scope, each newly declared variable gets assigned a number, so given var a, b, c we can access b as scope[1]. All scopes are numbered, and if this scope is nested five scopes deep, then b is fully addressed by env[5][1] which is known during parsing. In native code, scopes correspond to stack segments. Closures are a more complicated since they must back up and replace the env
    – amon
    Mar 16, 2015 at 8:00
  • @amon: That might be how you'd ideally like it to work, but it's not how it actually works. People far more knowledgeable and experienced than I have written books about this; in particular I'd point you to High Performance JavaScript by Nicholas C. Zakas. Here's a snippet, and he also did a talk with benchmarks to back it up. Of course he's certainly not the only one, just the most well-known. JavaScript has lexical scoping, so closures actually really aren't that special - essentially, everything is a closure.
    – Aaronaught
    Mar 17, 2015 at 4:43
  • @Aaronaught Interesting. Since that book is 5 years old, I was interested how a current JS engine handles variable lookups and looked at the V8 engine's x64 backend. During static analysis, most variables are resolved statically and are assigned a memory offset in their scope. Function scopes are represented as linked lists, and assembly is emitted as an unrolled loop to reach the correct scope. Here, we'd get the equivalent to the C code *(scope->outer + variable_offset) for an access; each extra function scope level costs one additional pointer dereference. Seems we were both right :)
    – amon
    Mar 18, 2015 at 13:11
2

One example involves a closure, the other does not. Implementing closures is kinda tricky, since closed over variables do not work like normal variables. This is more obvious in a low-level language like C, but I'll use JavaScript to illustrate this.

A closure does not only consist of a function, but also of all variables it closed over. When we want to invoke that function, we also need to provide all closed over variables. We can model a closure by a function that receives an object as first argument that represents these closed over variables:

function add(vars, y) {
  vars.x += y;
}

function getSum(vars) {
  return vars.x;
}

function makeAdder(x) {
  return { x: x, add: add, getSum: getSum };
}

var adder = makeAdder(40);
adder.add(adder, 2);
console.log(adder.getSum(adder));  //=> 42

Note the awkward calling convention closure.apply(closure, ...realArgs) this requires

JavaScript's builtin object support makes it possible to omit the explicit vars argument, and lets us use this instead:

function add(y) {
  this.x += y;
}

function getSum() {
  return this.x;
}

function makeAdder(x) {
  return { x: x, add: add, getSum: getSum };
}

var adder = makeAdder(40);
adder.add(2);
console.log(adder.getSum());  //=> 42

Those examples are equivalent to this code actually using closures:

function makeAdder(x) {
  return {
    add: function (y) { x += y },
    getSum: function () { return x },
  };
}

var adder = makeAdder(40);
adder.add(2);
console.log(adder.getSum());  //=> 42

In this last example, the object is only used to group the two returned function; the this binding is irrelevant. All the details of making closures possible – passing in hidden data to the actual function, changing all accesses to closure variables to lookups in that hidden data – are taken care of by the language.

But calling closures involves the overhead of passing in that extra data, and running a closure involves the overhead of lookups in that extra data – made worse by bad cache locality and usually a pointer dereference when compared with ordinary variables – so that it's not surprising that a solution that does not rely on closures performs better. Especially since everything your closure saves you to do is a few extremely cheap arithmetic operations, which might even be constant-folded during parsing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.