Closure vs static function

JavaScript performance comparison

Revision 4 of this test case created

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…
Closures from functions
function cl_f(x) {
  return function() {
    f(x)
  }
}

function cl_g(x, y) {
  return function() {
    g(x, y)
  }
}

function cl_h(x, y, z) {
  return function() {
    h(x, y, z)
  }
}

function cl_k(w, x, y, z) {
  return function() {
    k(w, x, y, z)
  }
}

var a = []

for (var i = 0; i < 50; i++) {
  for (var j = 0; j < 50; j++) {
    a.push(cl_f(i))
    a.push(cl_g(i, j))
    a.push(cl_h(i, j, i))
    a.push(cl_k(i, j, i, j))
  }
}

// 50*50*4 = 10000
for (var i = 0; i < 10000; i++)
a[i]()
pending…
Static function & arrays
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…
Static function & objects
function o(t, w, x, y, z) {
  this.t = t
  this.w = w
  this.x = x
  this.y = y
  this.z = z
}

function static_call(a) {
  if (a.t == 0) f(a.x)
  else if (a.t == 1) g(a.x, a.y)
  else if (a.t == 2) h(a.x, a.y, a.z)
  else if (a.t == 3) k(a.w, a.x, a.y, a.z)
}

var a = []

for (var i = 0; i < 50; i++) {
  for (var j = 0; j < 50; j++) {
    a.push(new o(0, i, i, j, i))
    a.push(new o(1, i, i, j, i))
    a.push(new o(2, i, i, j, i))
    a.push(new o(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