Closure in untaken path

Benchmark created by Marijn on


Description

Attempt to demonstrate the performance impact of having a closure in a function, even when that closure is never evaluated. Engines (at this point) allocate the space for the variables that the closure shares immediately when entering the function. By moving the closure into another function, the alternative test case ensures that it only pays this price when the closure is actually used.

Setup

function f_closure(x) {
      if (x < 0) {
        return [x].reduce(function(a, b) { return a + x + b; }, 0);
      } else {
        return x;
      }
    }
    
    function make_closure(x) {
      return function(a, b) { return a + x + b; };
    }
    
    function f_no_closure(x) {
      if (x < 0) {
        return [x].reduce(make_closure(x), 0);
      } else {
        return x;
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Closure in function
for (var i = 0, sum = 0; i < 1e6; i++)
  sum += f_closure(i);
ready
Closure external
for (var i = 0, sum = 0; i < 1e6; i++)
  sum += f_no_closure(i);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Marijn on