Re: switch statement
- Posted by mattlewis (admin) Mar 25, 2009
- 1357 views
Would it be faster to eval() when and only when () are encountered, or code like this:
case 1:
case 2:
case 3:
vs
case (x<4):
The first would probably be faster. If all cases are integers, then what happens when the switch happens, is that it first checks for the switching value's type. If it's not an integer, then it will end up at the case else (or after the entire switch, if there is no case else). If it is an integer, then if the difference between the largest and smallest is less than a certain value (1024, currently IIRC), then it uses a simple jump table, computed by the value of the integer (offset from the min value).
If the integers are too spread out, or if not all cases are integers, then it uses find() on the cases in combination with a jump table for the cases.
Assuming we were to implement your concept of a 'dynamic' switch, then I suspect they all might have to be evaluated. It might be possible to use the previous jump table, and if nothing there is found, then evaluate each remaining case in order, and jump if it evaluates as true. There might be better ways to do it.
Matt