Switch VS IF Else VS IF (v3)

Revision 3 of this benchmark created by imkrisna on


Description

The purpose of this test is to validate whether nested If-ElseIf conditions perform equally or more optimal than Switch statements and to compare my local test results against JSPerf's performance outcome.

According to local tests performed on my machine, it appears that the nested If-ElseIF conditions may perform the fastest but will eventually become sluggish as the 'variable-to-test' is tested against each conditional 'ElseIf' branch to find it's match.

In comparison, the 'Switch' statement maintains a consistent, favorable performance outcome whether testing against one 'case' or multiple 'case' branches. Lastly, the Multiple 'If' conditions resulted in the slowest performance of the three tested.

In conclusion (and my opinion), the 'Switch' statement performs very robust and provides a great value when evaluating against a long list of conditions. However, it may not always perform as equal as the 'If-ElseIf' conditional tests involving a short number of cases (e.g.. one to three nested conditions). Additionally, the 'Switch' statement offers a cleaner, visual style and structure in the code layout which can be beneficial to the code maintenance when evaluating a large number of conditions.

Test runner

Ready to run.

Testing in
TestOps/sec
IF-Else-IF
var subject = "toTest3";
var value;

for (var i = 0; i < 10000; i++) {
  if (subject === "toTest") {
    value = "cool1";
  } else if (subject === "toTest2") {
    value = "cool2";
  } else if (subject === "toTest3") {
    value = "cool3";
  } else if (subject === "toTest4") {
    value = "cool4";
  } else if (subject === "toTest5") {
    value = "cool5";
  }
}
ready
SWITCH
var subject = "toTest3";
var value;

for (var i = 0; i < 10000; i++) {
  switch (subject) {

    case "toTest":
      value = "cool";
      break;

    case "toTest2":
      value = "cool2";
      break;

    case "toTest3":
      value = "cool3";
      break;

    case "toTest4":
      value = "cool4";
      break;

    case "toTest5":
      value = "cool5";
      break;


  }
}
ready
Multiple IF conditions
var subject = "toTest3";
var value;

for (var i = 0; i < 10000; i++) {
  if (subject === "toTest") {
    value = "cool1";
  }
  if (subject === "toTest2") {
    value = "cool2";
  }
  if (subject === "toTest3") {
    value = "cool3";
  }
  if (subject === "toTest4") {
    value = "cool4";
  }
  if (subject === "toTest5") {
    value = "cool5";
  }
}
ready

Revisions

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

  • Revision 1: published by Adrian Sanoguel on
  • Revision 2: published by imkrisna on
  • Revision 3: published by imkrisna on
  • Revision 4: published on