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 :-)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With