Switch vs Object lookup (v2)

Revision 2 of this benchmark created on


Description

Simple benchmark to test speed of object lookup vs switch statement. TL;DR Faster in all browsers, but by varying degrees

Setup

const SOURCE = [
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0,
1,2,3,4,5,6,7,8,9,0
]
function double(x) {
  return 2 * x
}

Test runner

Ready to run.

Testing in
TestOps/sec
object
let handlers = {
	1: double,
	2: double,
	3: double,
	4: double,
	5: double,
	6: double,
	7: double,
	8: double,
	9: double,
	0: double,
}
function handle(x) {
  handlers[x](x)
}
// function call, object lookup, function call
SOURCE.map(handle)
ready
switch
function handle(x) {
	switch(x) {
		case 1: {double(x);break;}
		case 2: {double(x);break;}
		case 3: {double(x);break;}
		case 4: {double(x);break;}
		case 5: {double(x);break;}
		case 6: {double(x);break;}
		case 7: {double(x);break;}
		case 8: {double(x);break;}
		case 9: {double(x);break;}
		case 0: {double(x);break;}
	}
}
// function call, switch, function call
SOURCE.map(handle)
ready

Revisions

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