If statements

JavaScript performance comparison

Revision 10 of this 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":
  case "iteme":
  case "itemf":
  case "itemg":
  case "itemh":
  case "itemi":
  case "itemj":
  case "itemk":
  case "iteml":
  case "itemm":
  case "itemn":
  case "itemo":
  case "itemp":
  var x='123'+123;
}
pending…
~ and indexOf
if ( ~['itema','itemb','itemc','itemd',
       'iteme','itemf','itemg','itemh',
       'itemi','itemj','itemk','iteml',
       'itemm','itemn','itemo','itemp'].indexOf(ct) ) {
    var x='123'+123;
}
pending…
using | |
if (ct == 'itema' ||
    ct == 'itemb' ||
    ct == 'itemc' ||
    ct == 'itemd' ||
    ct == 'iteme' ||
    ct == 'itemf' ||
    ct == 'itemg' ||
    ct == 'itemh' ||
    ct == 'itemi' ||
    ct == 'itemj' ||
    ct == 'itemk' ||
    ct == 'iteml' ||
    ct == 'itemm' ||
    ct == 'itemn' ||
    ct == 'itemo' ||
    ct == 'itemp') {
    var x='123'+123;
}
pending…
using 'in' and Object
var possibilities = {
  "itema": 1,
  "itemb": 1,
  "itemc": 1,
  "itemd": 1,
  "iteme": 1,
  "itemf": 1,
  "itemg": 1,
  "itemh": 1,
  "itemi": 1,
  "itemj": 1,
  "itemk": 1,
  "iteml": 1,
  "itemm": 1,
  "itemn": 1,
  "itemo": 1,
  "itemp": 1
};
if (ct in possibilities) {
    var x='123'+123;
}
pending…
regex
if( /^item[a-p]$/.test(ct) ) {
  var x='123'+123;
}
pending…
Using 'in' and Function
if (ct in oc(['itema','itemb','itemc','itemd','iteme','itemf','itemg','itemh','itemi','itemj','itemk','iteml','itemm','itemn','itemo','itemp'])) { 
  var x='123'+123;
}

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)  o[a[i]]='';
  return o;
}
pending…
Object
if ({'itema':true,
     'itemb':true,
     'itemc':true,
     'itemd':true,
     'iteme':true,
     'itemf':true,
     'itemg':true,
     'itemh':true,
     'itemi':true,
     'itemj':true,
     'itemk':true,
     'iteml':true,
     'itemm':true,
     'itemn':true,
     'itemo':true,
     'itemp':true}[ct]) {
    var x='123'+123;
}
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