Switch vs. if/else (v6)

Revision 6 of this benchmark created on


Setup

var str = ['a', 'b', 'c', 'd', 'e', 'f', 'g'][Math.floor(Math.random() * 7)];
    
    function a() {
      console.log('a');
    }
    
    function b() {
      console.log('b');
    }
    
    function c() {
      console.log('c');
    }
    function d() {
      console.log('d');
    }
    function e() {
      console.log('e');
    }
    function f() {
      console.log('f');
    }
    function g() {
      console.log('g');
    }

Test runner

Ready to run.

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

map[str]();
ready
array
var arr = [a, b, c, d, e, f, g];
var x = 'abcdefg';

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

Revisions

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