result b (v2)

Revision 2 of this benchmark created on


Setup

// A function that may return null.
function rand() {
	return Math.random()
}

function Option1() {
	let n = rand();
	if (n < 0.5) {
		return null;
	}
	return n;
}

function Option2() {
	let n = rand();
	if (n < 0.5) {
		return { t: 0, v: null }
	}
	return { t: 1, v: n }
}

function Option(n) {
    this.t = 0;
    this.v = n;
}

const None = new Option(0);
const Some = (v) => {
	None.t = 1;
	None.v = v;
	return None;
}

function Option3() {
	let n = rand();
	if (n < 0.5) {
		return None;
	}
	return Some(n);
}

const CachedSome = Some(0);

function Option4() {
	let n = rand();
	if (n < 0.5) {
		CachedSome.v = n;
		return CachedSome;
	}
	return None;
}

Test runner

Ready to run.

Testing in
TestOps/sec
null
let n = 0;
for (let i = 0; i < 10000; i++) {
	let o = Option1();
	if (!o) n++;
}
ready
Manual option
let n = 0;
for (let i = 0; i < 10000; i++) {
	let o = Option2();
	if (!o.t) n++;
}
ready
func opt
let n = 0;
for (let i = 0; i < 10000; i++) {
	let o = Option3();
	if (!o.t) n++;
}
ready
Cached Some
let n = 0;
for (let i = 0; i < 10000; i++) {
	let o = Option4();
	if (!o.t) n++;
}
ready

Revisions

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