If-Else Chain VS Switch(true)

JavaScript performance comparison

Test case created by Jim

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 CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
If-Else Chain
for(var i = len; i--;) {
    var str = strs[i];
    
    if(/p{2}le/.test(str))
        var some_var = 'found apple';
    else if(/(an){2}a/.test(str))
        var some_var = 'found banana';
    else if(/^[a-z][a-z][a-z][a-z]$/.test(str))
        var some_var = 'found pear';
    else if(str.indexOf("lemon") != -1)
        var some_var = 'found lemon';
    else if(/ape/.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 /p{2}le/.test(str):
            var some_var = 'found apple';
            break;
        case /(an){2}a/.test(str):
            var some_var = 'found banana';
            break;
        case /^[a-z][a-z][a-z][a-z]$/.test(str):
            var some_var = 'found pear';
            break;
        case (str.indexOf("lemon") != -1):
            var some_var = 'found lemon';
            break;
        case /ape/.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.

4 Comments

Max commented :

I'm using FF14 and it says that the switch is slower...

Val commented :

Switch is slower for me on chrome 21...

Stu commented :

Interesting test. I actually wondered if using 'switch (true)' is better/worse than a standard if statement. I'd be interested to know if the results are similar with different code, e.g. using integers instead of strings.

Stuart commented :

Supposedly 'switch' out-performs 'if' on a large number of iterations..