if vs switch2

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/ext-core/3.1.0/ext-core.js">
</script>
<script>
  var a = 'hello',
      b = 'world',
      foo1, foo2;

  function test1(pValue) {
    if (pValue == a) return 'a'
    else if (pValue == b) return 'b'
  }

  function test2(pValue) {
    switch (pValue) {
    case a:
      return 'a';
      break;
    case b:
      return 'b';
      break;
    }
  }

  function test3(pValue) {
    switch (true) {
    case / hel / .test(pValue):
      return 'a';
      break;
    case / wo / .test(pValue):
      return 'b';
      break;
    }
  }
</script>

Preparation code output

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
foo1 = test1(a);
foo2 = test1(b);
pending…
case 1
foo1 = test2(a);
foo2 = test2(b);
pending…
case2
foo1 = test3(a);
foo2 = test3(b);
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