closure-vs-shared-method

JavaScript performance comparison

Test case created by Tim Caswell

Preparation code

<script>
// Shared methods with state stored in object instance.
function Vector(x, y) {
  this.x = x;
  this.y = y;
}
Vector.prototype.add = function (other) {
  return new Vector(this.x + other.x, this.y + other.y);
};
Vector.prototype.getLength = function () {
  return Math.sqrt(this.x * this.x + this.y * this.y);
};

function vectorCreate(x, y) {
  return {
    x: x,
    y: y,
    add: vectorAdd,
    getLength: vectorGetLength
  };
}
// Shared methods without constructor or inheritance.
function vectorAdd(other) {
  return vectorCreate(this.x + other.x, this.y + other.y);
}
function vectorGetLength() {
  return Math.sqrt(this.x * this.x + this.y * this.y);
}
 
// Closure state
function createVector(x, y) {
  return {
    x: x,
    y: y,
    add: add,
    getLength: getLength
  };
  function add(other) {
    return createVector(x + other.x, y + other.y);
  }
  function getLength() {
    return Math.sqrt(x * x + y * y);
  }
}
var len = 800;
var pVectors = new Array(len);
var oVectors = new Array(len);
var cVectors = new Array(len);
pVectors.length = 0;
for (var i = 0; i < len; i++) {
  var x = i % 20 - 10;
  var y = (i / 20) % 20 - 10;
  pVectors[i] = new Vector(x, y);
  oVectors[i] = vectorCreate(x, y);
  cVectors[i] = createVector(x, y);
}
function sum(list) {
  var total = list[0];
  for (var i = 0, l = list.length; i < l; i++) {
    total = total.add(list[i]);
  }
}
function dist(list) {
  var total = 0;
  for (var i = 0, l = list.length; i < l; i++) {
    total += list[i].getLength();
  }
}
</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
Prototype
sum(pVectors);
dist(pVectors);
pending…
Object
sum(oVectors);
dist(oVectors);
pending…
Closure
sum(cVectors);
dist(cVectors);
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