Cost of if else in loop

JavaScript performance comparison

Test case created by Carlos Vázquez

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var x,
      a = 1,
      b = 2,
      r, i;

};
</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
Duplicated for
r = Math.random();
if (r > 0.5) {
    for (i = 0; i < 10000; i++) {
        x = a + b;
    }
} else {
    for (i = 0; i < 10000; i++) {
        x = a - b;
    }
}
pending…
Unique for
r = Math.random();
for (i = 0; i < 10000; i++) {
    if (r > 0.5) {
        x = a + b;
    } else {
        x = a - b;
    }
}
pending…

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

1 Comment

Carlos Vázquez commented :

"Unique for" is slower (as expected) in Chrome (23%) and firefox (36%), but it is faster in Safari ("Duplicated for" being a 38% slower).