Finding ways to streamline your code can be rewarding in its own small way. Apart from making it look cool to others(!) and improve its readability there may be way to increase the execution speed of your code. Some time ago I wrote a mail with some examples with tricks you could use to do just that by using local variables etc. Recently I was thinking of some way to replace the structurally very nice byt also executionwise rather slow Switch statement. It turns out, that due to Hollywoods very flexible implementation of function and tables you can do just that and keep your code well structured too. Another case of something for nothing.
As an example, consider the following scenario...
You have a keyboard event handler to manage your program flow depending on which key you press. Keys are returned as values like "k" or "F1" or "LEFT" or some such string value.
Tables in Hollywood can use strings as index values. You can have a function as an element in a table. In other words, you can create a table of functions like this (The 'payload' of the functions in the example is of course rather pointless and just there for the example)
Code: Select all
MyTable = {}
Mytable["DEL"] = Function() n=n+1 EndFunction
MyTable["F1"] = Function() n=n+2 EndFunction
MyTable["LEFT"] = Function() n=n+3 EndFunction
What this means is that as an example your keyboard handler routine instead of multiple case statements in a Switch construction can look like this
Code: Select all
Function p_MyKeyboardHandler(msg)
if StrLen(msg.key)>1 /* Then we definitely have special keys */
dummy = MyTable[msg.key]()
else
/* Default key handling of regular keys like "k" or "v" */
endif
EndFunction
As a bonus the execution time of the code is just so much faster. I tested the example seen at the end of this mail. Execution time for the code based on function calls for any key returned was 867. Execution time for the Switch construction was at best (looking for the "LEFT" string as key response) 1889 and as a worst case (looking for "DEL") 3368.
Used as here for the decoding af keyboard responses, the code is not likely to be a part of a time critical main loop, so the speed up is hardly noticable. Most of the time the main loop is just wiating for the WaitEvent to deliver a key input or some other event. But if someone finds a need for the trick inside their main loop the gain is significant.
regards Jesper
Code: Select all
@DISPLAY {color = #SILVER}
direction$ = "LEFT"
local i,dummy
local n=0
StartTimer(1)
for i=1 to 100000
Switch direction$
case "LEFT":
n=n+1
case "RIGHT":
n=n+1
case "UP":
n=n+1
case "DOWN":
n=n+1
case "TAB":
n=n+1
case "DEL":
n=n+1
EndSwitch
next
nprint("Test 1: ",GetTimer(1))
StopTimer(1)
nprint(n)
Action = {}
action[direction$] = Function(arg) n=n+1 EndFunction
StartTimer(1)
for i=1 to 100000
dummy = action[direction$]()
next
nprint("Test 2: ",GetTimer(1))
StopTimer(1)
nprint(n)
waitleftmouse
end