codewars-calc-v2

JavaScript performance comparison

Test case created

Preparation code

<script>
  Benchmark.prototype.setup = function() {
    function evalbased(num1, operation, num2) {
      try {return eval(num1 + operation + num2)}
      catch(err) {return null};
    }
   
    function ifBased(num1, operation, num2) {
     if(operation == "+") return num1 + num2;
     if(operation == "-") return num1 - num2;
     if(operation == "/" && num2 != 0) return num1 / num2;
     if(operation == "*") return num1 * num2;
     return null;
    }
   
    function regExpBased(num1, operation, num2) {
      if (!/^[\+\-\*\/]$/.test(operation)) return null;
      return eval(num1 + operation + num2);
    }
   
   
    function arrayBased(num1, operation, num2) {
      if (['+', '-', '*', '/'].indexOf(operation) === -1 ||
          operation === '/' && num2 === 0) return null;
      return eval(num1 + operation + num2);
    }

function myOne(num1, operation, num2) {
  switch (operation) {
    case "+":
      return num1 + num2;
    case "-":
      return num1 - num2;
    case "*":
      return num1 * num2;
    case "/":
      return num2 == 0 ? null : num1 / num2;      
    default:
      return null;
  }
}
   
    function objectBased(num1, operation, num2) {
      var operators = {
        "+":function(a,b){return a+b;},
        "-":function(a,b){return a-b;},
        "*":function(a,b){return a*b;},
        "/":function(a,b){return ((b==0)?null:(a/b));}
      };
      operators[operation] = operators[operation] || function(){return null;};
      return operators[operation](num1,num2);
    }
  };
</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
evalBased
evalbased(1, "+", 2);
evalbased(1, "-", 2);
evalbased(1, "*", 2);
evalbased(1, "/", 2);
evalbased(1, "x", 2);
pending…
ifBased
ifBased(1, "+", 2);
ifBased(1, "-", 2);
ifBased(1, "*", 2);
ifBased(1, "/", 2);
ifBased(1, "x", 2);
pending…
regExpBased
regExpBased(1, "+", 2);
regExpBased(1, "-", 2);
regExpBased(1, "*", 2);
regExpBased(1, "/", 2);
regExpBased(1, "x", 2);
pending…
arrayBased
arrayBased(1, "+", 2);
arrayBased(1, "-", 2);
arrayBased(1, "*", 2);
arrayBased(1, "/", 2);
arrayBased(1, "x", 2);
pending…
objectBased
objectBased(1, "+", 2);
objectBased(1, "-", 2);
objectBased(1, "*", 2);
objectBased(1, "/", 2);
objectBased(1, "x", 2);
pending…
myOneBased
myOne(1, "+", 2);
myOne(1, "-", 2);
myOne(1, "*", 2);
myOne(1, "/", 2);
myOne(1, "x", 2);
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment