If-Else Chain VS Switch(true)

JavaScript performance comparison

Revision 5 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(/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…
big or
var ans = [
    'found else (orange)',
    'found apple',
    'found banana',
    'found pear',
    'found lemon',
    'found grape'
];
for(var i = len; i--;) {
    var str = strs[i];

    var some_var = ans[+(/p{2}le/.test(str) ||
        /(an){2}a/.test(str) * 2 ||
        /[a-z][a-z][a-z][a-z]/.test(str) * 3 ||
        str.indexOf("lemon") * 4 ||
        /ape/.test(str) * 5)];
}
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