IF vs IF-ELSE vs Switch Case vs Lookup Table - 2 Options (v2)

Revision 2 of this benchmark created on


Setup

function getRandomOption() {
    const options = ["Option 1", "Option 2", "unknown"];
    const randomIndex = Math.floor(Math.random() * options.length);
 
    return options[randomIndex];
}

const randomOption = getRandomOption();

Test runner

Ready to run.

Testing in
TestOps/sec
IF-ELSE-IF
if(randomOption === "Option 1") {
	console.log(1);
} else if(randomOption === "Option 2") {
	console.log(2);
} else {
	console.log('NONE')
}

ready
SWITCH-CASE
switch(randomOption) {
	case "Option 1": 
		console.log(1);
		break;
	case "Option 2": 
		console.log(2);
		break;
	default:
		console.log('NONE')
}

ready
Lookup Table
const results = {
	"Option 1": () => {
		console.log(1);
	},
	"Option 2": () => {
		console.log(2);
	},
}

results[randomOption] ? results[randomOption](): console.log('NONE')

ready
Bonus: Switch Pattern Matching
switch(true) {
	case randomOption === "Option 1": 
		console.log(1);
		break;
	case randomOption ===  "Option 2": 
		console.log(2);
		break;
	default:
		console.log('NONE')
}
ready

Revisions

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