Getter using Object map vs if

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
Using If
const getThing = (key = 'a') => {
	if (key === 'a') return 1
	else if (key === 'b') return 2
	else if (key === 'c') return 3
	else return 0
}
getThing()
getThing('c')
getThing('d')
ready
Using Object Map
const getThing = (key = 'a') => {
	return {
		'a': 1,
		'b': 2,
		'c': 3,
	}[key] || 0;
}
getThing()
getThing('c')
getThing('d')
ready
Using Switch
const getThing = (key = 'a') => {
	switch (key) {
		case 'a':
			return 1;
		case 'b':
			return 2;
		case 'c':
			return 3;
		default:
			return 0;
	}
}
getThing()
getThing('c')
getThing('d')
ready
Object map direct return
const getThing = (key = "a") =>
  ({
    a: 1,
    b: 2,
    c: 3,
  }[key] || 0);
getThing()
getThing('c')
getThing('d')
ready

Revisions

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