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;
}
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,
getLength: vectorGetLength
};
}
// Shared methods without constructor or inheritance.
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,
getLength: getLength
};
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++) {
}
}
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 CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Prototype
``````sum(pVectors);
dist(pVectors);``````
pending…
Object
``````sum(oVectors);
dist(oVectors);``````
pending…
Closure
``````sum(cVectors);
dist(cVectors);``````
pending…

Revisions

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