ternary operator vs. if statement

JavaScript performance comparison

Revision 8 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var j = 0;
   
    var rmd160_K1_1 = function(j) {
        return (0 <= j && j <= 15) ? 0x00000000 : (16 <= j && j <= 31) ? 0x5a827999 : (32 <= j && j <= 47) ? 0x6ed9eba1 : (48 <= j && j <= 63) ? 0x8f1bbcdc : (64 <= j && j <= 79) ? 0xa953fd4e : "rmd160_K1: j out of range";
    };
    var rmd160_K1_2 = function(j) {
        if (0 <= j && j <= 15) return 0x00000000;
        if (16 <= j && j <= 31) return 0x5a827999;
        if (32 <= j && j <= 47) return 0x6ed9eba1;
        if (48 <= j && j <= 63) return 0x8f1bbcdc;
        if (64 <= j && j <= 79) return 0xa953fd4e;
    };
    var rmd160_K1_3 = function(j) {
        if (0 <= j && j <= 15) return 0x00000000;
        else if (16 <= j && j <= 31) return 0x5a827999;
        else if (32 <= j && j <= 47) return 0x6ed9eba1;
        else if (48 <= j && j <= 63) return 0x8f1bbcdc;
        else if (64 <= j && j <= 79) return 0xa953fd4e;
    };
    var rmd160_K1_4 = function(j) {
        switch (true) {
            case 0 <= j && j <= 15:
                return 0x00000000;
            case 16 <= j && j <= 31:
                return 0x5a827999;
            case 32 <= j && j <= 47:
                return 0x6ed9eba1;
            case 48 <= j && j <= 63:
                return 0x8f1bbcdc;
            case 64 <= j && j <= 79:
                return 0xa953fd4e;
        }
    };
};

Benchmark.prototype.teardown = function() {
    j = Math.random * 80 |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
ternary
rmd160_K1_1();
pending…
if
rmd160_K1_2();
pending…
if-else
rmd160_K1_3();
pending…
switch
rmd160_K1_4();
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