Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoiding conditionals and function invocations inside a loop
    text
    copied!<p>I have a code that looks like this:</p> <pre class="lang-c prettyprint-override"><code>void function(int parameter) { for( ... ) // a big loop { double a = ...; for( ... ) // a big loop { double b = ...; double value; if(parameter == 1) value = some_math_expression_1(a, b); else if(parameter == 2) value = some_math_expression_2(a, b); ... } } } </code></pre> <p>The idea is that depending on the parameter I want to apply some math expression to <code>a</code> and <code>b</code>. This function is executed many times and must be fast, and I wonder if those conditional branches at each iteration can introduce an overhead that I could save. </p> <p>Right now, I have written the code like this:</p> <pre class="lang-c prettyprint-override"><code>void function(int parameter) { if(parameter == 1) function1(); else if(parameter == 2) function2(); else ... } </code></pre> <p>So that I can apply the math expression directly if I repeat the code in every <code>functionX()</code>. The obvious problem is that when I want to change some piece of code I have to do it several times (I have around 10 math expressions now). </p> <p>What approach could I use to avoid any overhead in <code>function</code>? </p> <p>What if I pass a pointer to functions <code>some_math_expression_X</code> to <code>function</code> (I would change the conditionals for function invocations)? </p> <p>What if I code the whole function as a macro (uf) and set the math expression as a parameter? </p> <p>What if I use a template and pass the math expression as a pointer to an inline function (is this even possible)?</p> <p><strong>EDIT</strong>: Thank you for your answers. I know I can use the methods you are proposing (pointers to / array of functions, or relying on the branch predictor). However, do you have some insight about what would be better in terms of avoiding overhead? The math expressions are quite simple (something like <code>a*b</code>), and in addition to the loops that are long, <code>function</code> is also called many times (do branch predictions "survive" between calls?).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload