I am trying to make my code more efficient and replace a bunch of if statements that I wrote. My program so far basically checks what operator (such as +, -, etc) is entered and then computes it. For example 1 + 5 gives 6. When the program evaluates the symbol between the number (the "+" in my example) it will check what the operator is and then proceed accordingly. For example if it's a "+", it will take the 1 and add 5. The code works like this:
switch (op) {
case "+": // Addition
return args[0] + args[1];
case "-": // Subtraction
return args[0] - args[1];
case "*": // Multiplication
return args[0] * args[1];
case "/": // Division
return args[0] / args[1];
I am wondering if it is possible to replace this whole block with some kind of statement that will detect the operator from the String and convert it into an operation? I realize for a few operators it is probably easier to use the switch statements but I have a lot of them and there is a 5-10ms difference between evaluating the operator at the top of the switch statements and at the bottom.
Aucun commentaire:
Enregistrer un commentaire