Domanda

Which will typically have better running time, multiple if blocks or a single if/else block?

if (statement1) {
    /* do something */
    return result;
}
if (statement2) {
    /* do something */
    return result;
}
if (statement3) {
    /* do something */
    return result;
}

Versus:

if (statement1) {
    /* do something */
    return result;
} else if (statement2) {
    /* do something */
    return result;
} else if (statement3) {
    /* do something */
    return result;
}

I've always used the first style when the logical statements weren't in any way related, and the second if they were.

EDIT

To clarify why this thought popped into my head, I am programming a prime checker and have an if block that looks something like this:

if(n<2) return 0;
if(n==2) return 1;
if(n%2==0) return 0;
...
È stato utile?

Soluzione

Which will typically have better running time, multiple if blocks or a single if/else block?

This is largely irrelevant as the semantics are different.

Now, if the goal is comparing the case of

if (a) { .. }
else if (b) { .. }
else { .. }

with

if (a) { return }
if (b) { return }
return

where no statements follow the conditional then they are the same and the compiler (in the case of a language like C) can optimize them equivalently.

Altri suggerimenti

Always go for if else if... when you know only one of the condition is to be executed, Writing multiple if's will make the compiler to check for each and every condition even when the first condition is met which will have a performance overhead, multiple if's can be used when u want to check and perform multiple operations based on certain condition

The if/else approach is faster, because it will skip evaluating the following conditions after one test succeeds.

However, the two forms are only equivalent if the conditions are mutually exclusive. If you just mindlessly convert one form into the other, you will introduce bugs. Make sure that you get the logic right.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top