Please pardon me if this is a duplicate question. I have two nested for loops which will iteration for around mn times (the complexity is around 3k).
Inside these for loops, I have 3 If conditions based on what I do certain operations. I am trying to see if there are any ways to avoid these if conditions inside the for loop as these will be executed for mn times.
Below is the skeletal of existing implementation:
var conditionA = <set conditions for A>
var conditionB = <set conditions for B>
var conditionC = <set conditions for C>
foreach (var x in X)
{
foreach (var y in Y)
{
if (conditionA)
{
//computeA ..makes use of x and y
}
if (conditionB)
{
//computeB..makes use of x and y
}
if (conditionC)
{
//computeC..makes use of x and y
}
} //end of inner foreach
}
As you can see that all the 3 conditions are determined before foreach
, is there any way I can get rid of redundant IF statements at each iteration?
computeA
,computeB
,computeC
. I wouldn't rely on this, but it suggests that you are optimizing prematurely. Take a look at a C++ and gcc example: https://godbolt.org/z/8oOwaW You have 3 conditions, so there are 8 ways in which the inner loop could run. Gcc generates code for each of these 8 ways and runs the inner loop without checking the conditions again. – pschill Jul 11 '19 at 08:23