If statements

JavaScript performance comparison

Test case created

Info

which one is faster from among ways at http://stackoverflow.com/questions/18347033/how-to-shorten-my-conditional-statements/18347354#18347354

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var test = {};
    test.type = 'itemc';
    var ct= test.type;
};
</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-case
switch (ct) {
  case "itema":
  case "itemb":
  case "itemc":
  case "itemd":
  var x='123'+123;
}
pending…
~ and indexOf
if ( ~['itema','itemb','itemc','itemd'].indexOf(ct) ) {
    var x='123'+123;
}
pending…
using | |
if (ct == 'itema' ||
    ct == 'itemb' ||
    ct == 'itemc' ||
    ct == 'itemd') {
    var x='123'+123;
}
pending…
using 'in' and Object
var possibilities = {
  "itema": 1,
  "itemb": 1,
  "itemc": 1,
  "itemd": 1
};
if (ct in possibilities) {
    var x='123'+123;
}
pending…
regex
if( /^item[a-d]$/.test(ct) ) {
  var x='123'+123;
}
pending…
Using 'in' and Function
if (ct in oc(['itema','itemb','itemc'])) { 
  var x='123'+123;
}

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)  o[a[i]]='';
  return o;
}
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