Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

constexpr array function pointers as fast as switch

24 views
Skip to first unread message

Larry Evans

unread,
Jul 6, 2010, 10:45:51 AM7/6/10
to
Is there any reason, other than compiler optimization limitations,
why, in the following code, dispatch_funvec should be any slower
than dispatch_switch. Are current implementations of dispatch_funvec
slower just because it's harder to optimize than the dispatch_switch.

TIA.

-regards,
Larry

-[---- cut here ----
unsigned value=0;

#define MAX_INDEX 3

template
< unsigned Index
>
unsigned fun(void)
{
value+=Index+1;
return value;
}

typedef unsigned(*fun_type)(void);
#ifdef CONSTEXPR_ENABLED
constexpr
#else
const
#endif
fun_type
fun_vec[MAX_INDEX]=
{ fun<0>
, fun<1>
, fun<2>
};

int dispatch_funvec(unsigned index)
{
return fun_vec[index]();
}

int dispatch_switch(unsigned index)
{
switch (index)
{
case 0:
return fun<0>();
case 1:
return fun<1>();
case 2:
return fun<2>();
default:
return -1;
}
}

-]---- cut here ----

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Bart van Ingen Schenau

unread,
Jul 6, 2010, 3:12:42 PM7/6/10
to
On Jul 6, 4:45 pm, Larry Evans <cppljev...@gmail.com> wrote:
> Is there any reason, other than compiler optimization limitations,
> why, in the following code, dispatch_funvec should be any slower
> than dispatch_switch. Are current implementations of dispatch_funvec
> slower just because it's harder to optimize than the dispatch_switch.

Basically, yes. dispatch_funvec is very much harder to optimise than
dispatch_switch, because indirect function calls (through a function
pointer) are very hard to expand inline. With functions as small (and
similar) as in your example, that could make a noticeable difference.

Bart v Ingen schenau

0 new messages