I have long used various optimization techniques, like walking pointers instead of accessing array via [ ]
indices. I knew that minimizing branching (if, else, case) made a difference, but I didn’t realize how much! My water thread is constantly updating all the 100x100 of single
water grids (just data) in the background. So it is a tight loop inside a tight and endless loop. I didn’t worry about its performance because it doesn’t affect the foreground. But now that there can be many of these grids (up to over 100 so far) you could see the slowness of the water update.
I removed a bunch of if then else if then else
situations… (3 branches) with 1 case statement. This made a notable improvement in performance!
for example
if aboolean1 then
begin
blahblah1
end
else
if aboolean2 then
begin
blahblah2
end
else
begin
blahblah3
end;
becomes
var whichcase : integer;
whichcase := ord( aboolean1 ) + ord( aboolean2 ) shl 1;
case whichcase of
0: blahblah3;
1, 3 : blahblah1; { note is two possibilities as includes aboolean2 in 2nd bit, but just checking bit1 }
2 : blahblah2;
end;
also when just setting values like
var delta : single;
if aboolean1 then
delta := somevalue1
else
if aboolean2 then
delta := somevalue2
else
delta := 0;
becomes
delta := ord( aboolean1 ) * somevalue1 + ord( aboolean2 ) * somevalue2;
These two types of optimizations to reduce branching seemed to double the speed the water flow updates tiles. It had a lot of branching. Now it has almost none, especially in the tighest loops.