fabiosantoscode / js2cpp

A toy js -> c++ compiler written in coffeescript. Uses escodegen to write c++ and tern to figure out types.
110 stars 11 forks source link

Not all closures necessarily need to be allocated on the heap. #2

Open fabiosantoscode opened 8 years ago

fabiosantoscode commented 8 years ago

After flattening in dumbjs, closures are turned into javascript objects. Then all variables that need to be in a closure are accessed and updated through the similarly-named properties in those objects.

It is known that it's impossible to implement closures by storing them solely on the stack. This is because it's impossible to cover all of their features without placing them on the heap. It is also necessary to have a garbage collector that will destroy them after they're not necessary anymore.

However, there are cases where a closure may be created on the stack. For example:

var one = 1;
function addOne(x) {
  return x + one
}
console.log(addOne(1))
console.log(addOne(2))

The addOne function doesn't outlive its relevant stack frame. As such, its closure (containing just the variable called one) could live in the stack.

This is advantageous in examples such as the one above, since allocating this structure on the heap would mean more work for the garbage collector, and slower access to its values.

Another example:

var count = 0
[1,2,3].forEach(function addToCount (val) { count += val })

The function addToCount above is passed to another function (forEach), but it doesn't outlive the stack frame because forEach returns before this stack frame is done and doesn't store addToCount anywhere. This is another example in which a function's closure can be declared on the stack for faster access.