Cast/Convert variable into array instead of using ifelse

JavaScript performance comparison

Revision 2 of this test case created and last updated

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function withoutIfElse(variable) {
      var variables, len, i;
   
      if (!variable) {
        return; // or throw an exception
      }
   
      variables = Array.isArray(variable) ? variable : [variable];
      len = variables.length;
   
      for (i = 0; i < len; i++) {
        console.log(variables[i]);
      }
    }
   
    function ifElse(variable) {
      var len, i;
   
      if (!variable) {
        return; // or throw an exception
      }
   
      len = variable.length;
   
      if (Array.isArray(variable)) {
        for (i = 0; i < len; i++) {
          console.log(variable[i]);
        }
      } else {
        console.log(variable[i]);
      }
    }
   
    function withforEach(variable) {
   
      if (!variable) {
        return; // or throw an exception
      }
   
      variables = Array.isArray(variable) ? variable : [variable];
   
      variables.forEach(function(value) {
        console.log(value);
      });
    }
};
</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
withifelse
ifElse(42)
pending…
withoutifelse
withoutIfElse(42)
pending…
withforEach
withforEach(42)
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