Best way to conditionally execute a function?
Yes, I know the wording is difficult to understand, but this is what really hurts me. In a recent project I have a function that recurses and there are a number of conditions that would cause it to stop recursing (three at the moment). Which situation would be optional? (IE best performance or ease of maintenance).
1) Conditional refund:
void myRecursingFunction (int i, int j){
if (conditionThatWouldStopRecursing) return;
if (anotherConditionThatWouldStopRecursing) return;
if (thirdConditionThatWouldStopRecursing) return;
doSomeCodeHere();
myRecursingFunction(i + 1, j);
myRecursingFunction(i, j + 1);
}
2) Wrap the whole thing in an if statement
void myRecursingFunction (int i, int j){
if (
!conditionThatWouldStopRecursing &&
!anotherConditionThatWouldStopRecursing &&
!thirdConditionThatWouldStopRecursing
){
doSomeCodeHere();
myRecursingFunction(i + 1, j);
myRecursingFunction(i, j + 1);
}
}
3) You are doing it wrong noob, no sane algorithm will ever use recursion.
source to share
Both of these approaches should result in the same IL code behind the scenes since they are equivalent to boolean expressions. Note that each termination condition will be evaluated in the order in which you write it (since the compiler cannot figure out which is most likely), so you will want to set the most common termination condition first.
Although structured programming dictates the second approach is better, I personally prefer the code to return conditions as a separate block at the top of the recursive method. I find it easier to read and read (although I'm not a fan of returns in random areas of the method body).
source to share
If this is what should be fast, I would recommend using the most common case as quickly as possible (i.e. putting the base case at the end, because you will only hit it once). Also consider putting base register-1 in front of the recursive clause (i.e., do the test before you call the function again, rather than checking it when writing to a subsequent call) if that would make a difference.
And, with all this stuff, don't optimize unless it's a problem. I went for clarity first.
source to share