Benno Kress
Benno Kress

Reputation: 2809

How are consecutive if statements evaluated?

I have two if-statements to check, where one check is very costly. So I'm wondering which of the following statements would be the most performant:

1) I don't like the "pyramid of doom", but I'm sure it works fine

for customObject in array {
    if customObject.isSimpleBool {
        if customObject.isCostlyBool {
            // do some stuff
        }
    }
}

2) I normally write like this ... but does it check isCostlyBool, if isSimpleBool is false?

for customObject in array {
    if customObject.isSimpleBool && customObject.isCostlyBool {
        // do some stuff
    }
}

3) I know this works, but is it evaluated differently than solution 2?

for customObject in array {
    if customObject.isSimpleBool, customObject.isCostlyBool {
        // do some stuff
    }
}

4) Is there another solution I have not found?

Upvotes: 0

Views: 81

Answers (3)

Luca Angeletti
Luca Angeletti

Reputation: 59496

As already stated in there comments, if we have boolean expression like this

a && b

and a is false then the result is evaluated as false only evaluating a.

So...

isSimpleBool && isCostlyBool

is evaluated as false without evaluating isCostlyBool when isSimpleBool is false.

This is a good reason why you should put the isSimpleBool value at the left side of the && operator.

Another syntax

Finally just another way of writing the same logic

for elm in array where elm.isSimpleBool && elm.isCostlyBool {
    // do some stuff
}

Upvotes: 1

Jacob Boyd
Jacob Boyd

Reputation: 690

for customObject in array {
    if customObject.isSimpleBool && customObject.isCostlyBool {
        // do some stuff
    }
}

This will work, I have used these kinds of statements with nil checks many times.

if (obj != nil && obj!.property == false) {}

and in cases of obj being nil, obj.property is never called(otherwise the application would crash)

Upvotes: 2

vadian
vadian

Reputation: 285069

Another solution:

array.filter { $0.isSimpleBool && $0.isCostlyBool }
     .forEach { // do some stuff } 

By the way: Solution 2 and 3 are different forms for the same thing.

Upvotes: 1

Related Questions