Re: switch bug?
- Posted by mattlewis (admin) Jul 21, 2008
- 853 views
Is if...elsif...endif just as fast as the switch statement?
I was thinking that switch should be faster than if ... elsif ... end if, however this benchmark suggests that if ... elsif ... end if is faster. Matt, what are your thoughts?
Basically, it's showing how the switch construct is not optimized.
Currently, switch is implemented using find. This means that it was pretty easy to do, but isn't always the fastest. There is some overhead for the call, of course. The if-elsif construct seems to degrade quicker if there are 'dead' options. Also, if you happen to have a sequence comparison in there, switch seems to work better.
Having said that, I have been thinking about some ways to optimize switch. For switches that are all small integers, for instance, it could simply do a type and bounds test and use a lookup on the jump table, rather than having to use find to figure out where to go. This should blow away the if-elsif construct at the cost of a bit of memory.
There are probably other optimizations. Here is a modified example with a few dead options, plus a sequence. If you change a to an object or an atom, the swtich looks better yet.
integer a = 20 atom t0 t0 = time() for b = 1 to 100000000 do switch a do case 0: a = -1 break case 5: a = 10 break case -1: a = -2 break case 10: a = 15 break case "foo": a = 0 break case 15: a = 20 break case -2: a = -3 break case 20: a = 25 break case 25: a = 30 break case -3: a = -4 break case 30: a = 35 break case -4: case else a = 5 end switch end for printf(1, "switch=%f\n", {time()-t0}) t0 = time() for b = 1 to 100000000 do if a = 0 then a = -1 elsif a = 5 then a = 10 elsif a = -1 then a = -2 elsif a = 10 then a = 15 elsif equal( a, "foo" ) then a = 0 elsif a = 15 then a = 20 elsif a = -2 then a = -3 elsif a = 20 then a = 25 elsif a = -3 then a = -4 elsif a = 25 then a = 30 elsif a = 30 then a = 35 elsif a = -4 then a = -5 else a = 5 end if end for printf(1, "if=%f\n", {time()-t0})
Matt