Javascript classes vs. prototype

Benchmark created on


Setup

class Operation {
	constructor(a, b) {
		this.a = a;
		this.b = b;
		this.r = 0;
	}
	operate() {
		this.r = this.a + this.b;
	}
}

function getRandomInt(max) {
  return Math.floor(Math.random() * max);
}

const SIZE = 10_000;
var opsObjects = [];
var opsProtos = [];
for(let i = 0; i < SIZE; i++) {
	const a = getRandomInt(SIZE);
	const b = getRandomInt(SIZE);
	const opObject = new Operation(a, b);
	opsObjects.push(opObject);
	opProto = {a:a, b:b, r:0};
	opsProtos.push(opProto);
}

Test runner

Ready to run.

Testing in
TestOps/sec
Test objects
for(let i = 0; i < opsObjects.length; i++) {
	const opObject = opsObjects[i];
	opObject.operate();
}
ready
Test protos
for(let i = 0; i < opsProtos.length; i++) {
	var opProto = opsProtos[i];
	opProto.r = opProto.a + opProto.b;
}
ready

Revisions

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