If-Else Chain VS Switch(true)

JavaScript performance comparison

Revision 3 of this test case created

Info

This test is to attempt to determine if there is any notable performance difference when using switch(true) instead of a chain of if-else statements.

Preparation code

<script>

var strs = ['apple','banana','pear','lemon','grape','orange'], len = strs.length;

</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
If-Else Chain
for(var i = len; i--;) {
    var str = strs[i];
   
    if(str === "apple")
        var some_var = 'found apple';
    else if(str === "banana")
        var some_var = 'found banana';
    else if(str === "pear")
        var some_var = 'found pear';
    else if(str === "lemon")
        var some_var = 'found lemon';
    else if(str === "grape")
        var some_var = 'found grape';
    else
        var some_var = 'found else (orange)';
}
pending…
switch(true)
for(var i = len; i--;) {
    var str = strs[i];
   
    switch(true) {
        case (str === "apple"):
            var some_var = 'found apple';
            break;
        case (str === "banana"):
            var some_var = 'found banana';
            break;
        case (str === "pear"):
            var some_var = 'found pear';
            break;
        case (str === "lemon"):
            var some_var = 'found lemon';
            break;
        case (str === "grape"):
            var some_var = 'found grape';
            break;
        default:
            var some_var = 'found else (orange)';
    }  
}
pending…
switch
for(var i = len; i--;) {
    var str = strs[i];
   
    switch(str) {
        case "apple":
            var some_var = 'found apple';
            break;
        case "banana":
            var some_var = 'found banana';
            break;
        case "pear":
            var some_var = 'found pear';
            break;
        case "lemon":
            var some_var = 'found lemon';
            break;
        case "grape":
            var some_var = 'found grape';
            break;
        default:
            var some_var = 'found else (orange)';
    }  
}
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