another switch vs object vs if

Benchmark created on


Setup

var getFromMap = (function(){
    var map = {
       foo: 1,
       bar: 2,
       doh: 3,
       baz: -1
    };
    return function(n) {
        return map[n] || 0;
    };
    })();
    
    function getFromSwitch(n) {
        switch(n) {
        case 'foo': return 1;
        case 'bar': return 2;
        case 'doh': return 3;
        case 'baz': return -1;
        default: return 0;
        }
    };
    
    function getFromIf(n) {
        if (n == 'foo') return 1;
        if (n == 'bar') return 2;
        if (n == 'doh') return 3;
        if (n == 'baz') return -1;
        return 0;
    };
    var ret = 0;

Test runner

Ready to run.

Testing in
TestOps/sec
map
ret += getFromMap('foo');
ret += getFromMap('bar');
ret += getFromMap('doh');
ready
switch
ret += getFromSwitch('foo');
ret += getFromSwitch('bar');
ret += getFromSwitch('doh');
ready
if
ret += getFromIf('foo');
ret += getFromIf('bar');
ret += getFromIf('doh');
ready

Revisions

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