Case against switch-case

Benchmark created by netpoetica on


Description

Use functions + dictionary instead of Switch/Case

Setup

// Setup
    function onGet(){ /* .. */ }
    function onDelete(){ /* .. */ }
    function onPost(){ /* .. */ }
    var onPut = onPost; // Sharing functionality.
    
    // Extra Setup
    var methodHandlers = {
      get: onGet,
      delete: onDelete,
      post: onPost,
      put: onPut
    };
    
    // Bad
    function processRequestWithCase(method){
      var requestMethod = method.toLowerCase();
    
      switch(requestMethod){
        case "get":
          onGet();
          break;
        case "delete":
          onDelete();
          break;
        // Can be dangerous, also not good for readability
        case "post":
        case "put":
          onPost();
          break;
      }
    }
    
    function processRequestWithDictionary(method){
      var requestMethod = method.toLowerCase();
    
      // Get  reference to the method so we don't do a lookup twice
      var handler = methodHandlers[requestMethod];
     
      // If we have a handle, run it.
      if(typeof handler === 'function') handler();
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Using switch/case
processRequestWithCase("get");
processRequestWithCase("post");
processRequestWithCase("delete");
processRequestWithCase("put");
 
ready
Using dictionary/function
processRequestWithDictionary("get");
processRequestWithDictionary("post");
processRequestWithDictionary("put");
processRequestWithDictionary("delete");
ready

Revisions

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

  • Revision 1: published by netpoetica on