Reputation: 615
Is there any difference between using an if/else
statement and the ternary operator
in Objective C in terms of speed? Are they identical in compiled code?
That is, is there any reason to use one of the following over the other, other than to save space?
//First Option
Object *myObj = boolean ? trueValue : falseValue;
//Second Option
Object *myObj;
if (boolean) {
myObj = trueValue;
else {
myobj = falseValue;
}
Upvotes: 1
Views: 414
Reputation: 726589
Although there may be minor differences in compiled code, there is no reason other than readability to prefer one way to the other.
One advantage of the if
/else
approach is that you can set up multiple variables with a single condition:
Object *myObj1;
Object *myObj2;
if (boolean) {
myObj1 = trueValue1;
myObj2 = trueValue1;
else {
myobj1 = falseValue2;
myobj2 = falseValue2;
}
Since boolean in Objective-C is a numeric type with values 0 and 1, there is an approach that does not rely on conditionals at all:
Object *valArray[] = { falseValue, trueValue };
Object *myObj = valArray[boolean];
Upvotes: 1