Switch Statement vs. Dictionary Object: Functions Edition

Benchmark created on


Test runner

Ready to run.

Testing in WebKit 537.36 / undefined
TestOps/sec
Switch statement
const executeCommand = command => {
  switch (command) {
    case 'greet':
      console.log('Hello there!');
      break;
    case 'farewell':
      console.log('Goodbye!');
      break;
    case 'time':
      console.log(`Current time: ${new Date().toLocaleTimeString()}`);
      break;
    default:
      console.log('Unknown command');
  }
};

executeCommand('greet'); // 'Hello there!'
executeCommand('time'); // 'Current time: 12:34:56'
ready
Dictionary Object
const executeCommand = command => {
  const commands = {
    greet: () => console.log('Hello there!'),
    farewell: () => console.log('Goodbye!'),
    time: () => console.log(`Current time: ${new Date().toLocaleTimeString()}`),
    default: () => console.log('Unknown command')
  };

  // Execute the command if it exists, otherwise execute the default command
  (commands[command] || commands.default)();
};

executeCommand('greet'); // 'Hello there!'
executeCommand('time'); // 'Current time: 12:34:56'
ready

Revisions

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