Switch statement vs single if logic

JavaScript performance comparison

Revision 2 of this test case created

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
function sizeToBytes(size, format) {

        "use strict";

        switch (format) {
        case 'MB':
                return size * 1048576;
        case 'GB':
                return size * 1073741824;
        case 'TB':
                return size * 1099511627776;
        default:
                return size * 1024;
        }

}

var test = sizeToBytes(1,'KB');
pending…
Single If Logic
function size(amount, format) {
    var sizes = {
        'MB': 1048576,
        'GB': 1073741824,
        'TB': 1099511627776
    }

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

    return amount * 1024;
}

var test = size(1,'KB');
pending…
Switch (with variables)
function sizeToBytes(size, format) {

        "use strict";

        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;
        }

}
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