Hersh Bhargava
Hersh Bhargava

Reputation: 615

Ternary Operator vs. If/Else in Objective C

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

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions