Maximizing speed of a switch block

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Hi everyone,

We have a critical loop which looks like this: (I'll simplify to the
extreme)

enum type { ... };

struct X
{
type t_;
virtual void doIt();
};


type t_ is (conceptually) public because it can change after object
creation.
so X behaviour cannot rely entirely of virtual functions.
later there's a loop on all X objects


for (int i=0; i<N; ++i)
{
X* x = get(i);
switch (x->t_)
{
case type1: // possibly change i...
break;

case type2: // possibly change N...
break;

// ...more cases here

default:
x->doIt();
break;
}
}


someone proposed to rewrite this loop as follows:
(I hope my barebone example is not too simple)


struct allMyVars
{
int i;
int N;
....
};

typedef void (*action_Func)(X*, allMyVars*);

struct X
{
action_Func f;
virtual void doIt();
};

void action_1(X*, allMyVars* v)
{
// update whatever
v.i = 37;
}

void default_action(X* x, allMyVars*)
{
x->doIt();
}


// ...

allMyVars v;
for (v.i=0; v.i<v.N; ++v.i)
{
X* x = get(v.i);
(x.f)(x, &v);
}



my question is: rewriting code like this would be a moderately-serious
activity, so no way we just do it and profile execution time later. Is
there any reason why a function-pointer jump would be faster than an
enum-based switch?

Thanks for sharing conjectures
MH
.



Relevant Pages

  • avoid cast to derived
    ... userBase objects, ... struct Base{virtual void method=0;}; ... virtual void user1(Base& obj){obj.method;} ...
    (comp.object)
  • Re: Pattern Protestations.
    ... oops make the pointer derferencing look prettier. ... struct D: X { ... virtual void f ...
    (comp.object)
  • Re: Call to a virtual method crashes
    ... It doesn't matter. ... virtual void f; ... struct Y1: X ... Microsoft MVP - Visual C++ ...
    (microsoft.public.vc.mfc)
  • Re: Threads on class,
    ... I have to admit that I was wrong - the ... DWORD ThreadId; ... virtual void f; ...
    (microsoft.public.windowsce.embedded.vc)
  • Re: Threads on class,
    ... I have to admit that I was wrong - the ... DWORD ThreadId; ... virtual void f; ...
    (microsoft.public.vc.language)