Gernot Frisch wrote:
OK. What's the fastest way of doing:
void MyBMPClass::Draw()
{
for (x ...)
for (y ...)
switch(mode)
I assume that 'mode' is a constant within 'Draw()' and that speed
is your ultimate goal, i.e. you would accept a reasonable increase
in code size. The approach using a switch statement within the
inner loop is probably better than using a function pointer due to
the function call overhead (as noted in my previous article or by
Pete Becker). If 'mode' is indeed constant within your function,
you would get still better performance using something like
switch (mode)
{
case 0:
for (x ...)
for (y ...)
Func0(x, y);
break;
case 1:
for (x ...)
for (y ...)
Func1(x, y);
break;
...
}
Of course, you typically don't want to repeat the code, especially
if it is even more than just the two nested loops. In this case,
you might try to do it like this:
template <void (*func)(int, int)>
void DrawAux()
{
for (x ...)
for (y ...)
func(x, y);
}
void Draw(int mode)
{
switch (mode)
{
case 0: DrawAux<Func0>(); break;
case 1: DrawAux<Func1>(); break;
...
}
}
Whether the compiler optimizes this code to avoid the function call
is, of course, depending on the compiler. You will need to profile
this.
BTW, rather than using a switch statement in the above, you might
also try to use a virtual function: the virtual function dispatch
in the inner loop may be too expensive but putting the loop into
the function may well warrant the virtual function.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting