Dispatch Tables VS Conditionals

JavaScript performance comparison

Test case created by Richard Dillman

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Case Statement
function processUserInput(command) {

  'use strict';
  switch (command) {
  case "north":
    movePlayer("north");
    break;
  case "east":
    movePlayer("east");
    break;
  case "south":
    movePlayer("south");
    break;
  case "west":
    movePlayer("west");
    break;
  }
}
pending…
If statements
function processUserInput(command) {

  'use strict';
  if (command === 'north') {
    movePlayer("north");
  }
  if (command === 'north') {
    movePlayer("east");
  }
  if (command === 'south') {
    movePlayer("south");
  }
  if (command === 'west') {
    movePlayer("west");
  }
}
pending…
Dispach Table
var commandTable = {
  north: function() {

    'use strict';
    movePlayer("north");
  },
  east: function() {

    'use strict';
    movePlayer("east");
  },
  south: function() {

    'use strict';
    movePlayer("south");
  },
  west: function() {

    'use strict';
    movePlayer("west");
  },
}

function processUserInput(command) {

  'use strict';
  commandTable[command]();
}
pending…
Single Internal function
function processUserInput(command) {

  'use strict';
  if (['north', 'east', 'south', 'west'].indexOf(command) !== -1) {
    movePlayer(command);
  }
}
pending…

Compare results of other browsers

Revisions

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

1 Comment

Kyle Knight commented :

Your if statement section has a typo

  if (command === 'north') {
    movePlayer("east");
  }