Switch vs. if/else (v8)

Revision 8 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
concise test
if (str === 'a') a();
if (str === 'b') b();
if (str === 'c') c();
if (str === 'd') d();
if (str === 'e') e();
if (str === 'f') f();
if (str === 'g') g();
ready

Revisions

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