Closure vs static function

JavaScript performance comparison

Revision 3 of this test case created by shkdee

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function f(x) {
      var y = x + 1
      return y
    }
   
    function g(x, y) {
      var z = x + y
      return z
    }
   
    function h(x, y, z) {
      var w = x + y + z
      return w
    }
   
    function k(w, x, y, z) {
      var v = w + x + y + z
      return v
    }
};
</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
var a = []

for (var i = 0; i < 50; i++) {
  for (var j = 0; j < 50; j++) {
    a.push(function() {
      var x = i
      f(x)
    })
    a.push(function() {
      var x = i,
          y = j
           g(x, y)
    })
    a.push(function() {
      var x = i,
          y = j,
          z = i
           h(x, y, z)
    })
    a.push(function() {
      var w = i,
          x = j,
          y = i,
          z = j
           k(w, x, y, z)
    })
  }
}

// 50*50*4 = 10000
for (var i = 0; i < 10000; i++)
a[i]()
pending…
Static functions
function static_call(a) {
  if (a[0] == 0) f(a[1])
  else if (a[0] == 1) g(a[1], a[2])
  else if (a[0] == 2) h(a[1], a[2], a[3])
  else if (a[0] == 3) k(a[1], a[2], a[3], a[4])
}

var a = []

for (var i = 0; i < 50; i++) {
  for (var j = 0; j < 50; j++) {
    a.push([0, i])
    a.push([1, i, j])
    a.push([2, i, j, i])
    a.push([3, i, j, i, j])
  }
}

// 50*50*4 = 10000
for (var i = 0; i < 10000; i++)
static_call(a[i])
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:

0 comments

Add a comment