I have a code that looks like this:
void function(int parameter) { for( ... )
The idea is that depending on the parameter, I want to apply a mathematical expression to a and b . This function is performed many times and should be fast, and I wonder if these conditional branches can introduce overheads at each iteration, which I could save.
Right now, I wrote the code as follows:
void function(int parameter) { if(parameter == 1) function1(); else if(parameter == 2) function2(); else ... }
So, I can apply the math expression directly if I repeat the code in each functionX() . The obvious problem is that when I want to change part of the code, I have to do this several times (now I have about 10 mathematical expressions).
What approach can be used to avoid overhead in function ?
What if I pass a pointer to some_math_expression_X function on function (I would change the conventions for invocations functions)?
What if I encode the entire function as a macro (uf) and set the math expression as a parameter?
What if I use a template and pass a mathematical expression as a pointer to an inline function (is this possible)?
EDIT : Thanks for your answers. I know that I can use the methods you suggest (pointers to / an array of functions or rely on a branch predictor). However, do you have any idea what would be better in terms of preventing overhead? The math expressions are pretty simple (something like a*b ), and in addition to long loops, function also called many times (branch predictions “survive” between calls?).
source share