Switch vs object literal

Benchmark created by Warren Rumak on


Setup

function getSnackSwitch(type) {
    
            var drink;
            switch (type) {
            case 'coke':
                drink = 'Coke';
                break;
            case 'pepsi':
                drink = 'Pepsi';
                break;
            default:
                drink = 'Unknown drink!';
            }
    
            return drink;
        }
    
        function getSnackOL(type) {
            var snack;
    
            function isDrink() {
                return snack = 'Coke';
            }
    
            function isFood() {
                return snack = 'Pepsi';
            }
    
            var snacks = {
                'coke': isDrink,
                'pepsi': isFood
            };
            return snacks[type]();
        }

Test runner

Ready to run.

Testing in
TestOps/sec
one
    for (var i = 0; i < 10; i++) {
        var x;
        if (i % 2 === 0)
            x = getSnackSwitch('coke');
        else if (i % 2 === 1)
            x = getSnackSwitch('pepsi');
    }
 
ready
two
    for (var i = 0; i < 10; i++) {
        var x;
        if (i % 2 === 0)
            x = getSnackOL('coke');
        else if (i % 2 === 1)
            x = getSnackOL('pepsi');
    }
 
ready

Revisions

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