My code has unnecessary if/else conditions. Will they affect the performance of my code? If they are taken out, does it have any effect on execution time of the program?
- 1,031,962
 - 187
 - 1,923
 - 1,875
 
- 44
 - 1
 - 9
 
- 
                    3Any concrete example? Why are these unnecessary conditions left in the code in the first place if they are unnecessary? – JB Nizet May 07 '17 at 08:22
 
3 Answers
My code has unnecessary if/else conditions. Will they affect the performance of my code?
If they're executed, they take non-zero time to evaluate. But in 99.99999% of cases, it's unlikely to matter. Worry about a performance problem when you have a performance problem.
But for example, given:
void example(int a) {
    if (a < 0) {
        doThis();
    } else if (a < 100) {
        doThat();
    } else if (a < 1000) {
        doSomethingElse();
    } else {
        doAnotherThingEntirely();
    }
}
...if you know that a will never be, say, <50, those first two conditions are unnecessary, they'll never be true. Checking them requires doing work — a very very very very very small amount of work that's unlikely to matter, but work nonetheless. So in that sense, it affects your code's performance.
But again: It's unlikely to matter. Worry about it when you're dealing with a real-world performance problem you've isolated to the code in question.
That doesn't mean you shouldn't remove them. If they're truly unnecessary, they're exactly that: Unnecessary. Unnecessary code should generally be removed, all other things being equal.
- 1,031,962
 - 187
 - 1,923
 - 1,875
 
In general it will not affect the performance but can cause unexpected behaviour. In terms of Clean Code unneserry if and if-else statements have to be removed for clarity, maintainability, better testing.
One case where the performance will be reduced because of unnecessary if statements is in loops.
- 151
 - 6