Answer the question
In order to leave comments, you need to log in
switch analogy
There is a long, long switch for a thousand-plus cases on the packet parser.
Attention, the question is:
is this thing more efficient:
char k;
typedef void(*fptr)();
fptr t[65535];
void a(){k='a';}
void b(){k='b';}
void c(){k='c';}
void* (func)();
void main ()
{
memset(t,0,sizeof(t));
t[0]=&a;
t[1]=&b;
t[2]=&c;
unsigned short i;
cin>>i;
//ключевой кусок
t[i] ? t[i]() : t[i];
printf("k=%c",k);
//конец ключевого куска
_getch();
}
Answer the question
In order to leave comments, you need to log in
Your “thing” is more efficient both in terms of design and speed. switch is generally not the best choice.
Only I would replace it
if(t[i]!=NULL){
g =(void(*)()) t[i];
g(); //или g(); - аналогично
printf("k=%c",k);
}
t[i] ? t[i]() : t[i];
Most likely or equally, or the switch is more effective.
The performance of the switch does not depend on the size, since there is still a jump table there.
If the goal is to improve performance, I would advise starting with profiling and finding really slow places; replacing the switch with an array of functions will do nothing in this regard.
1) what kind of efficiency is the question about: speed, code size, code clarity?
2) the proposed code is unambiguously supplemented by checking the admissible range i.
According to the tests that I conducted, a well-built elseif (with the most common cases on top) worked on large volumes much faster than a similar switch, which cannot be set to the “most frequent options”
(poked in the wrong place, the answer is in the thread of the second comment)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question