Switch vs if/else

JavaScript performance comparison

Test case created by Joshua Kehn

Preparation code

<script>
  var init_arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
</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
Switch
var arr_len = init_arr.length,
    total = 0;
while (arr_len--) {
 var v = init_arr[arr_len];
 switch (v) {
 case 1:
  total += v;
  break;
 case 2:
  total += v + 2;
  break;
 case 3:
  total += v + 3;
  break;
 case 4:
  total += v + 4;
  break;
 case 5:
  total += v + 5;
  break;
 case 6:
  total += v + 6;
  break;
 case 7:
  total += v + 7;
  break;
 case 8:
  total += v + 8;
  break;
 case 9:
  total += v + 9;
  break;
 case 10:
  total += v + 10;
  break;
 }
}
pending…
If / Else
var arr_len = init_arr.length,
    total = 0;
while (arr_len--) {
 var v = init_arr[arr_len];

 if (v == 1) {
  total += v + 1;
 } else if (v == 2) {
  total += v + 2;
 } else if (v == 3) {
  total += v + 3
 } else if (v == 4) {
  total += v + 4;
 } else if (v == 5) {
  total += v + 5;
 } else if (v == 6) {
  total += v + 6;
 } else if (v == 7) {
  total += v + 7;
 } else if (v == 8) {
  total += v + 8;
 } else if (v == 9) {
  total += v + 9;
 } else if (v == 10) {
  total += v + 10;
 }
}
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