Code Selection: property lookup+function call vs if-else

JavaScript performance comparison

Test case created

Info

The idea behind this is that we switch the codepath that we're running only very rarely. Should we make the actual codepath selection every time we loop or only at the time we actually change it?

(Test 1 implicates that we use (at the time of change) if-else to change the module into some other module which also has the func property.)

This test tries to see if which code selection strategy has the bigger penalty.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var counterTestModule = (function() {
        var value =0;
       
        var func = function() {
            value = value + 1;
        }
       
        var getValue = function() {
            return value;
        }
       
        var reset = function() {
            value = 0;
        }
       
        return {
            func: func,
            getVal: getValue,
            reset: reset
        }
    })();
   
    var test1 = 'PLUSONE';
    var test2 = 'PLUSTWO';
    var test3 = 'PLUSTHREE';
    var value = 0;
};

Benchmark.prototype.teardown = function() {
    value = 0;
};
</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
Property lookup and function call
counterTestModule.func();
 
pending…
If-else, when first one hits
if (test1==='PLUSONE') {
    value = value + 1;
} else if (test1==='PLUSTWO') {
    value = value + 2;
} else if (test1==='PLUSTHREE') {
    value = value + 3;
}
pending…
If-else, when second one hits
if (test2==='PLUSONE') {
    value = value + 1;
} else if (test2==='PLUSTWO') {
    value = value + 2;
} else if (test2==='PLUSTHREE') {
    value = value + 3;
}
pending…
If-else, when third one hits
if (test3==='PLUSONE') {
    value = value + 1;
} else if (test3==='PLUSTWO') {
    value = value + 2;
} else if (test3==='PLUSTHREE') {
    value = value + 3;
}
pending…
If-else, when first one hits, with different operand to sum (just in case...)
if (test1==='PLUSONE') {
    value = value + 3;
} else if (test1==='PLUSTWO') {
    value = value + 2;
} else if (test1==='PLUSTHREE') {
    value = value + 1;
}
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment