Switch vs. if/else

Benchmark created by Jason on


Setup

var str = ['a', 'b', 'c'][Math.floor(Math.random() * 3)];
    
    function a() {
      console.log('a');
    }
    
    function b() {
      console.log('b');
    }
    
    function c() {
      console.log('c');
    }

Test runner

Ready to run.

Testing in
TestOps/sec
switch
switch(str) {
  case 'a':
    a();
    break;
  case 'b':
    b();
    break;
  case 'c':
    c();
    break;
}
ready
if/else
if (str === 'a') {
  a();
} else if (str === 'b') {
  b();
} else if (str === 'c') {
  c();
}
ready
map
var map = {
  a: a,
  b: b,
  c: c
};

map[str]();
ready
array
var arr = [a, b, c];
var x = 'abc';

arr[x.indexOf(str)]();
ready

Revisions

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