Is a switch statement the fastest way to implement operator interpretation in Java
        Posted  
        
            by Mordan
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Mordan
        
        
        
        Published on 2010-03-23T19:44:32Z
        Indexed on 
            2010/03/23
            20:33 UTC
        
        
        Read the original article
        Hit count: 545
        
Is a switch statement the fastest way to implement operator interpretation in Java
   public boolean accept(final int op, int x, int val) {
     switch (op) {
        case OP_EQUAL:
          return x == val;
        case OP_BIGGER:
          return x > val;
        case OP_SMALLER:
          return x < val;
        default:
          return true;
     }
   }
In this simple example, obviously yes. Now imagine you have 1000 operators. would it still be faster than a class hierarchy? Is there a threshold when a class hierarchy becomes more efficient in speed than a switch statement? (in memory obviously not)
abstract class Op {
 abstract public boolean accept(int x, int val);
}
And then one class per operator.
© Stack Overflow or respective owner