Switch statement vs single if logic

JavaScript performance comparison

Revision 4 of this test case created by Erik Corry

Preparation code

<script>
function sizeToBytesSwitch(size, format) {
        switch (format) {
        case 'MB':
                return size * 1048576;
        case 'GB':
                return size * 1073741824;
        case 'TB':
                return size * 1099511627776;
        default:
                return size * 1024;
        }

}
function sizeToBytesObject(amount, format) {
    var sizes = {
        'MB': 1048576,
        'GB': 1073741824,
        'TB': 1099511627776
    }

    if(sizes[format]) {
        return amount * sizes[format];
    }

    return amount * 1024;
}
var sizes = {
    'MB': 1048576,
    'GB': 1073741824,
    'TB': 1099511627776
}

function sizeToBytesObjectOnce(amount, format) {
    if(sizes[format]) {
        return amount * sizes[format];
    }

    return amount * 1024;
}
var sizes2 = {
    'KB': 1024,
    'MB': 1048576,
    'GB': 1073741824,
    'TB': 1099511627776
}

function sizeToBytesObjectOncePositive(amount, format) {
    if(sizes2[format]) {
        return amount * sizes2[format];
    }

    return amount * 1024;
}

function sizeToBytesVariables(size, format) {
        var KBYTES_IN_BYTES   = 1024,
            MEGABYTE_IN_BYTES = 1048576,
            GIGABYTE_IN_BYTES = 1073741824,
            TERABYTE_IN_BYTES = 1099511627776;

        switch (format) {
        case 'MB':
                return size * MEGABYTE_IN_BYTES;
        case 'GB':
                return size * GIGABYTE_IN_BYTES;
        case 'TB':
                return size * TERABYTE_IN_BYTES;
        default:
                return size * KBYTES_IN_BYTES;
        }

}
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Switch
for (var i = 7; i < 1000000; i *= 13) {
  var test = sizeToBytesSwitch(i,'KB');
}
pending…
Object lookup
for (var i = 7; i < 1000000; i *= 13) {
  var test = sizeToBytesObject(i,'KB');
}
pending…
Switch (with variables)
for (var i = 7; i < 1000000; i *= 13) {
  var test = sizeToBytesVariables(i,'KB');
}
pending…
Object lookup hoisted
for (var i = 7; i < 1000000; i *= 13) {
  var test = sizeToBytesObjectOnce(i,'KB');
}
pending…
Positive object lookup hoisted
for (var i = 7; i < 1000000; i *= 13) {
  var test = sizeToBytesObjectOncePositive(i,'KB');
}
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment