If-Else Chain VS Switch(true)

JavaScript performance comparison

Revision 4 of this test case created by Ben Truyman

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>
Benchmark.prototype.setup = function() {
    var strs = ['apple','banana','pear','lemon','grape','orange'],
        len = strs.length;
   
    var first = /p{2}le/,
        second = /(an){2}a/,
        third = /^[a-z][a-z][a-z][a-z]$/,
        forth = /ape/;
};
</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(first.test(str))
        var some_var = 'found apple';
    else if(second.test(str))
        var some_var = 'found banana';
    else if(third.test(str))
        var some_var = 'found pear';
    else if(str.indexOf("lemon") != -1)
        var some_var = 'found lemon';
    else if(forth.test(str))
        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 first.test(str):
            var some_var = 'found apple';
            break;
        case second.test(str):
            var some_var = 'found banana';
            break;
        case third.test(str):
            var some_var = 'found pear';
            break;
        case (str.indexOf("lemon") != -1):
            var some_var = 'found lemon';
            break;
        case forth.test(str):
            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