Are there any differences in the general compute time in the following two scenarios? I remember learning in school that you should have the if statement run more often than the else statement (if possible), but wasn't really given any reasoning as to why this would be the case.
Lets say for both situations, condition
is more likely than not to be true (for example, condition
is true
75% and false
25% of the time).
Scenario 1:
for(int i=0; i<10000; ++i) {
if(condition) {
//do something
} else {
//do something else
}
}
Scenario 2:
for(int i=0; i<10000; ++i) {
if(!condition) {
//do something else
} else {
//do something
}
}
I guess the question boils down to, are there any speed differences between checking the if condition, running the do something
code, and then branching to the end of the if/else statement compared to branching at the beginning and then running the do something
code?
Edit:
Like many comments and answers have stated, there is likely no change in speed in these two different scenarios listed above. The situation I was remembering from school was in regards to nested if/else loops in which the following:
if(mostLikelyCondition) {
if(lessLikelyCondtion) {
//do something
} else {
//do something else
} else {
//do other something else
}
would be faster than this:
if(lessLikelyCondition) {
if(moreLikelyCondition) {
//do something
} else {
//do something else
} else {
//do other something else
}