switch vs object literal vs module (v21)

Revision 21 of this benchmark created by anon on


Preparation HTML

<script>

function getDrink1(type) {
    switch (type) {
        case 'coke':
            type = 'Coke';
            break;
        case 'pepsi':
            type = 'Pepsi';
            break;
        case 'lemonade':
            type = 'Lemonade';
            break;
    }
    return type;
}

function getDrink2(type) {
    if (type === 'coke') {
        type = 'Coke';
    } else if (type === 'pepsi') {
        type = 'Pepsi';
    } else if (type === 'lemonade') {
        type = 'Lemonade';
    }
    return type;
}

function getDrink3(type) {
    var drinks = {
        'coke': 'Coke',
        'pepsi': 'Pepsi',
        'lemonade': 'Lemonade'
    };
    return drinks[type];
}

function getDrink4(type) {
    return {
        'coke': 'Coke',
        'pepsi': 'Pepsi',
        'lemonade': 'Lemonade'
    }[type];
}

    var drinks = {
        'coke': 'Coke',
        'pepsi': 'Pepsi',
        'lemonade': 'Lemonade'
    };

function getDrink5(type) {
    return drinks[type];
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
switch
getDrink1('lemonade');
ready
if else
getDrink2('lemonade');
ready
object literal 1
getDrink3('lemonade');
ready
object literal 2
getDrink4('lemonade');
ready
cached object literal
getDrink5('lemonade')
ready

Revisions

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