views:

75

answers:

3

Does Objective-C evaluate every statement on an if... else if... block or does it evaluate each as it comes to them and then skip the remaining evaluations if a true condition has been found?

This is more of a pragmatic question related to performance than anything else.

And yes I do know that the content of the if block itself isn't executed, but I am referring to the actual statements that get evaluated.

Example

if ([condition A] == test) {
  // Do something
} else if ([condition B] == test) {
  // Do something    
} else if ([condition C] == test) {
  // Do something    
} else {
  // Do something because all other tests failed
}    

So... if condition A is true, do conditions B and C get evaluated anyway?

If they do, then does using a switch statement perform the same way or does a switch only test each condition as it comes to it and then exits the evaluation because of the break?

My understanding is that on an if... else if... block, every condition is evaluated and therefore using a switch or nested if's (ugh - don't relish the thought there) might be faster on big evaluation operations on a lot of data (hundreds of thousands of items being checked against potentially a hundred statements).

Just curious :-)

+5  A: 

No, if condition A is met, B and C are not evaluated. Indeed, they are part of the else-clauses that won't get executed then anyway.

Just a side note: if (condA || condB) or if (condA && condB) also evaluates lazily, i.e. in the first case condB is only evaluated if condA is false, in the second case when condA is true.

Eiko
Eiko - the side note could actually come in handy and was for me the next natural extension to the question... Great to know. Thanks.
Hooligancat
The computer sciency term is 'short-circuit evaluation'. See http://en.wikipedia.org/wiki/Short_circuit_evaluation
Andrew
+4  A: 

It only evaluates them as it comes to them. An if ... else if block is equivalent to if.. else {if...}. It behaves the same way as nested ifs, it's just formatted nicely and omits some braces.

JoshD
Thanks Josh. Good to know I had it wrong! :-)
Hooligancat
+2  A: 

Outside of the []'s objective-c behaves in exactly the same way that C does.

For if() ... else if() ... else ... chains that means each expression is evaluated until one evaluates to true and the block is entered. Basically

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

is interpreted as

if (a) {
    ...
} else {
    if (b) {
        ...
    } else {
        ...
    }
}
olliej
Olliej - thanks for the feedback. This is all good news for my code :-)
Hooligancat