Switch vs Object Literal largerestbestfixed

4 years ago
User agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36
Test name Executions per second
Switch 55682.1 Ops/sec
Object Literal 53395.1 Ops/sec
Script Preparation code:
x
 
var str = 'q';
var objLiteral = {
  a: function() {
    console.log('A');
  },
  b: function() {
    console.log('B');
  },
  c: function() {
    console.log('C');
  },
  d: function() {
    console.log('D');
  },
  e: function() {
    console.log('E');
  },
  f: function() {
    console.log('F');
  },
  g: function() {
    console.log('G');
  },
  h: function() {
    console.log('H');
  },
  i: function() {
    console.log('I');
  },
  j: function() {
    console.log('J');
  },
  k: function() {
    console.log('K');
  },
  l: function() {
    console.log('L');
  },
  m: function() {
    console.log('M');
  },
  n: function() {
    console.log('N');
  },
  o: function() {
    console.log('O');
  },
  p: function() {
    console.log('P');
  },
  q: function() {
    console.log('Q');
  },
  r: function() {
    console.log('R');
  },
  s: function() {
    console.log('S');
  },
  t: function() {
    console.log('T');
  },
  u: function() {
    console.log('U');
  },
  v: function() {
    console.log('V');
  },
  w: function() {
    console.log('W');
  },
};
var switchtest = (str) => {
  switch (str) {
  case 'a': console.log('A'); break;
  case 'b': console.log('B'); break;
  case 'c': console.log('C'); break;;
  case 'd': console.log('D'); break;;
  case 'e': console.log('E'); break;;
  case 'f': console.log('F'); break;;
  case 'g': console.log('G'); break;;
  case 'h': console.log('H'); break;;
  case 'i': console.log('I'); break;;
  case 'j': console.log('J'); break;;
  case 'k': console.log('K'); break;;
  case 'l': console.log('L'); break;;
  case 'm': console.log('M'); break;;
  case 'n': console.log('N'); break;;
  case 'o': console.log('O'); break;;
  case 'p': console.log('P'); break;;
  case 'q': console.log('Q'); break;;
  case 'r': console.log('R'); break;;
  case 's': console.log('S'); break;;
  case 't': console.log('T'); break;;
  case 'u': console.log('U'); break;;
  case 'v': console.log('V'); break;;
  case 'w': console.log('W'); break;
}
}
Tests:
  • Switch

     
    switchtest(str);
  • Object Literal

     
    objLiteral[str]();
Open this result on MeasureThat.net