Soft Private vs Hard Private (v2)

Revision 2 of this benchmark created on


Setup

const $softPrivate = Symbol();

class SoftPrivateClass {
	[$softPrivate] = 0;
	
	add() {
		this[$softPrivate] += 1;
	}
	
	get() {
		return this[$softPrivate];
	}
}

const hardMap = new WeakMap()
class HardPolyfillClass {	
	constructor() {
		hardMap.set(this, 0);
	}
	
	add() {
		hardMap.set(this, hardMap.get(this) + 1)
	}
	
	get() {
		return hardMap.get(this);
	}
}

class HardPrivateClass {
	#hardPrivate = 0;
	
	add() {
		this.#hardPrivate += 1;
	}
	
	get() {
		return this.#hardPrivate;
	}
}

function runSoft() {
	const sc = new SoftPrivateClass();
	
	for (let i = 0; i < 10000; ++i) {
		sc.add();
	}
	
	console.assert(sc.get() === 10000);
}

function runHardPolyfill() {
	const hc = new HardPolyfillClass();
	
	for (let i = 0; i < 10000; ++i) {
		hc.add();
	}
	
	console.assert(hc.get() === 10000);	
}
function runHard() {
	const hc = new HardPrivateClass();
	
	for (let i = 0; i < 10000; ++i) {
		hc.add();
	}
	
	console.assert(hc.get() === 10000);	
}

Test runner

Ready to run.

Testing in
TestOps/sec
Soft Private
runSoft()
ready
Hard Private
runHard()
ready
Hard Private (Polyfill)
runHardPolyfill()
ready

Revisions

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