array vs optional (v3)

Revision 3 of this benchmark created on


Setup

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

for (let i = 0; i < 9999; i++) {
	const arrobj = {
		num: i % 3,
		opt: []
	};
	const optobj = {
		num: i % 3,
	};
	const r = Math.random();
	if (i % 2 === 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(obj) {
	for (const fn of obj.opt) {
		arrResult = fn(arrResult);
	}
}

for (let i = 0; i < arrTest.length; i++) {
	const obj = arrTest[i];
	if (obj.num == 0) {
		next(obj);
	}
}
ready
Opt Opt
optionalResult = 0;

function next(obj) {
	const fn = obj.opt;
	if (fn) {
		optionalResult = fn(optionalResult);
	}
}

for (let i = 0; i < optionalTest.length; i++) {
	const obj = optionalTest[i];
	if (obj.num == 0) {
	    next(obj);
	}
}
ready
Arr Inline
arrResult = 0;

for (let i = 0; i < arrTest.length; i++) {
    const obj = arrTest[i];
	if (obj.num == 0) {
	    for (const fn of obj.opt) {
		    arrResult = fn(arrResult);
	    }
	}
}
ready
Obj Inline
optionalResult = 0;

for (let i = 0; i < optionalTest.length; i++) {
	const obj = optionalTest[i];
	if (obj.num == 0) {
	    const fn = obj.opt;
	    if (fn) {
		    optionalResult = fn(optionalResult);
	    }
	}
}
ready

Revisions

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