0
votes

I want to create a single function interface with a function that takes an ID and a parameter struct. Internally, functions are called and parameters from the struct are passed to the function. the returning values are passed to pointers in the struct. What are some pitfalls in this design? Is there anything that is faster than a switch-case statement?

enum Id{ CALL_1, CALL_2};
struct PARM_1 { int parm1; int parm2; void* data};
struct PARM_2 { int parm1; int* parm2};

void function(int id, void* parm)
{
  switch (id)
  {
   case CALL_1:
   {
    PARM_1* p = (struct PARM_1*) parm;
    function_1(p->parm1, p->parm2, parm->data); 
    break;
   }
  case CALL_2:
   {
    PARM_2* p = (struct PARM_2*) parm;
    function_2(p->parm1, p->parm2);
    break;
   }
  default:
    break;
}

}

void foo(int parm1, int parm2, void data); void barint parm1, int parm2);

1
Please edit the post and fix indention. And ensure your code editor is set to not indent with tabs but instead to insert spaces. - Lundin
Casts from and to void* are unnecessary. - Quentin

1 Answers

2
votes

First of all, the standard rule of thumb for doing manual optimizations. Generally, manual code optimizations don't make much sense unless:

  • You have benchmarked your code and found out that a certain part of it is a bottleneck.
  • You have a given hardware in mind.
  • You are an expert of the given hardware.

That being said, a C programmer will always have to ensure that they aren't writing stupidly inefficient things that the compiler can't very well do much about. For example complex nested loop constructs, complex nested if-elses, complex function calls, recursion etc etc.


In this specific case, the code looks good, there's not really much you can do to improve performance.

A switch-case like this one, based on an enum with adjacent numbers, are ideal for the optimizer. The compiler can optimize it into an array of function pointers, each function pointer corresponding to a case. Or alternatively into an array of direct jump addresses.

It is not really something the C programmer needs to concern themselves with, but they may need to consider that a switch where every integer case is an adjacent number likely gets better optimized than a switch with any random numbers.

In this case, the only optimization concern is probably branch prediction. But since you are using different function signatures, there's not really a way to avoid it. If you could rewrite the functions to use the same signatures, the function could be optimized ever so slightly. But we are talking nanoseconds here.