Switch vs. lookup

Benchmark created on


Description

Determining if switch is faster than return object[value]

Setup

const table = {
};

for (let i = 0; i < 26; i++) {
	table[String.fromCharCode(i + 65)] = i;
}
Object.freeze(table);

const randoms = [];

for (let i = 0; i < 500; i++) {
	randoms.push(String.fromCharCode(65 + Math.floor(Math.random() * 26)));
}


const withRandoms = (fn) => {
	for (let i = 0; i < randoms.length; i++) {
		const input = randoms[i];
		fn(input);
	}
}

Test runner

Ready to run.

Testing in
TestOps/sec
Switch
withRandoms((input) => {
	switch (input) {
case "A": return 0;
case "B": return 1;
case "C": return 2;
case "D": return 3;
case "E": return 4;
case "F": return 5;
case "G": return 6;
case "H": return 7;
case "I": return 8;
case "J": return 9;
case "K": return 10;
case "L": return 11;
case "M": return 12;
case "N": return 13;
case "O": return 14;
case "P": return 15;
case "Q": return 16;
case "R": return 17;
case "S": return 18;
case "T": return 19;
case "U": return 20;
case "V": return 21;
case "W": return 22;
case "X": return 23;
case "Y": return 24;
case "Z": return 25;
default: throw new Error("");
	}
})
ready
Obj
withRandoms((input) => {
	if (input in table) {
		return table[input];
	}
	throw new Error("");
});
ready

Revisions

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