array vs optional

Benchmark created on


Setup

arrTest = [];
optionalTest = [];
arrResult = 0;
optionalResult = 0;

for (let i = 0; i < 9999; i++) {
	const arrobj = {
		opt: []
	};
	const optobj = {};
	const r = Math.random();
	if (i % 3 === 0) {
		const fn = (arg) => {
		    return r + arg;	
		};
		arrobj.opt.push(fn);
		optobj.opt = fn;
	}
	arrTest.push(arrobj);
	optionalTest.push(optobj);
}

Teardown

console.log(arrResult, optionalResult);

Test runner

Ready to run.

Testing in
TestOps/sec
Array Opt
arrResult = 0;

function next(arr, i) {
	const obj = arr[i];
	for (const fn of obj.opt) {
		arrResult = fn(arrResult);
	}
}

for (let i = 0; i < arrTest.length; i++) {
	next(arrTest, i);
}
ready
Opt Opt
optionalResult = 0;

function next(arr, i) {
	const obj = arr[i];
	const fn = obj.opt;
	if (fn) {
		optionalResult = fn(optionalResult);
	}
}

for (let i = 0; i < optionalTest.length; i++) {
	next(optionalTest, i);
}
ready

Revisions

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