Page 1 of 1

Some ways of making you Hollywood code faster

Posted: Sun Feb 28, 2010 12:55 pm
by TheMartian
While looking at ways of optimizing the code in one of my programs I did a small test on some appearently straightforward code that surely must be in use in many places. To my surprise a change in this simple code gave a considerable speed increase. The test was made on a 733MHz SAM-Flex.

I use the code for managing the movement of a cursor in a textbox, but similar code can be found in games where an object is moved this or that way depending on a condition. In the example I have just used the value True to represent the test.

My testexample ran as follows

starttimer(1)
for i=1 to 100000
if true
v=v+1
else
v=v-1
endif
next
nprint(gettimer(1),v)

waitleftmouse
end

This example returns a timer value of about 1000. It hardly matters whether the condition is true or false. The result is close to 1000 in both cases.

It is well known, that changing variables into local variables will speed up things. If I add the line...

Local i,v=0,0

...the time returned is about 875. No surprises there, and you probably do this all the time as recommended in the manual.

Now replace this code:

if true
v=v+1
else
v=v-1
endif

with this code:

v=v+1
if True Then v=v-2

...and suddenly the timer returns about 660. Again it matters little whether the condition returns True or False. Cutting 25% from the execution time is not bad. The basic trick is to always set one of the two outcomes (as a default) and then use the simpler If/Then construction instead of If/Then/Else to modify the outcome if the condition is true.

Another observation is that code seems to execute faster when run from a window than if using full-screen mode. It is just a few percent and consistent no matter which window size you use - even if you set the window to the same as the full screen size (1920x1200 in my case). I added a Wait(100) statement before starting the timer and running the test loop. So the screen setup should not be a factor as far as I can see. If I don't do this it does affect the result.

regards
Jesper