Closure vs static function

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function f(x) {
      var y = x + 1
      return y
    }
   
    function g(x) {
      var y = x - 1
      return y
    }
   
    function static_call(a) {
      if (a[1] == 0) f(a[0])
      else if (a[1] == 1) g(a[0])
    }
   
    var a = []
    var b = []
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Closures
for (var i = 0; i < 1000; i++) {
  a.push(function() {
    f(i)
  })
  a.push(function() {
    g(i)
  })
}

for (var i = 0; i < 2000; i++)
a[i]()
pending…
Static functions
for (var i = 0; i < 1000; i++) {
  b.push([i, 0])
  b.push([i, 1])
}

for (var i = 0; i < 2000; i++)
static_call(b)
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

shkdee commented :

This one is wrong (last line of "static functions" case should be "static_call(b[i])"), see revision 2.

Add a comment