If-Else Chain VS Switch(true)

JavaScript performance comparison

Revision 7 of this test case created

Info

This test is to attempt to determine if there is any notable performance difference when using switch(true) instead of a chain of if-else statements.

Preparation code

<script>
  var strs = ['apple', 'banana', 'pear', 'lemon', 'grape', 'orange'],
      len = strs.length;
</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
If-Else Chain
for (var i = len; i--;) {
  var str = strs[i];

  if (/p{2}le/.test(str)) var some_var = 'found apple';
  else if (/(an){2}a/.test(str)) var some_var = 'found banana';
  else if (/^[a-z][a-z][a-z][a-z]$/.test(str)) var some_var = 'found pear';
  else if (str.indexOf("lemon") != -1) var some_var = 'found lemon';
  else if (/ape/.test(str)) var some_var = 'found grape';
  else var some_var = 'found else (orange)';
}
pending…
switch(true)
for (var i = len; i--;) {
  var str = strs[i];

  switch (true) {
  case / p {
      2
    }
    le / .test(str):
    return 'found apple';
  case / (an) {
      2
    }
    a / .test(str):
    return 'found banana';
  case / ^ [a - z][a - z][a - z][a - z] $ / .test(str):
    return 'found pear';
  case (str.indexOf("lemon") != -1):
    return 'found lemon';
  case / ape / .test(str):
    return 'found grape';
  default:
    return 'found else (orange)';
  }
}
pending…
ternary
for (var i = len; i--;) {
  var str = strs[i];

  var some_var = /p{2}le/.test(str) ? 'found apple' : /(an){2}a/.test(str) ? 'found banana' : /^[a-z][a-z][a-z][a-z]$/.test(str) ? 'found pear' : (str.indexOf("lemon") != -1) ? 'found lemon' : /ape/.test(str) ? 'found grape' : 'found else (orange)';
}
pending…
short-circuit
for (var i = len; i--;) {
  var str = strs[i];

  var some_var = /p{2}le/.test(str) && 'found apple' || /(an){2}a/.test(str) && 'found banana' || /^[a-z][a-z][a-z][a-z]$/.test(str) && 'found pear' || (str.indexOf("lemon") != -1) && 'found lemon' || /ape/.test(str) && 'found grape' || 'found else (orange)';
}
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