Object literal vs. switch statement lookup performance

Benchmark created by Geoff Little on


Setup

var keys = ['1', '2', '3', '4', '5', '6', '7'];
  
  var objectLiteral = {
    '1': true,
    '2': true,
    '3': true,
    '4': true,
    '5': true,
    '6': true,
    '7': true,
  };
  
  function objectLiteralLookup(key, value) {
    if (typeof value === 'object') {
      return value;
    }
    return objectLiteral[key] ? value : undefined;
  };
  
  function switchStatementLookup(key, value) {
    if (typeof value === 'object') {
      return value;
    }
    switch (key) {
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
        return value;
      default:
        return undefined;
    }
  };
  
  function arrayLookup(key, value) {
    if (typeof value === 'object') {
      return value;
    }
    return keys.includes(key) ? value : undefined;
  };
  
  
  var input = {
    '1': 'a',
    '2': 'a',
    '3': 'a',
    '4': 'a',
    '5': 'a',
    '6': 'a',
    '7': 'a',
    '8': 'a',
    '9': 'a',
  };

Test runner

Ready to run.

Testing in
TestOps/sec
Object literal
JSON.stringify(input, objectLiteralLookup)
ready
Switch statement
JSON.stringify(input, switchStatementLookup)
ready
Array literal
JSON.stringify(input, arrayLookup)
ready

Revisions

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

  • Revision 1: published by Geoff Little on