0

Which is better performance?

Option 1

var sections: [SubMenu]

var selectedItem: BeverageItem? {
    var item: BeverageItem?
    for section in sections {
        for beverage in section.beverages {
            if beverage.isSelected {
                item = beverage
                break
            }
        }
    }
    return item
}

Option 2

var selectedItem: BeverageItem? {
    var item: BeverageItem?
    if let subMenuIndex = sections.index(where: { (subMenu) -> Bool in
        for beverage in subMenu.beverages {
            if beverage.isSelected {
                return true
            }
        }
        return false
    }) {
        let subMenu = sections[subMenuIndex]
        if let beverageIndex = subMenu.beverages.index(where: { (beverage) -> Bool in
            return beverage.isSelected
        }) {
            item = subMenu.beverages[beverageIndex]
        }
    }
    return item
}

If option 1 then where would you use option 2 and why?

3
  • 8
    How large are your arrays? Unless they are very large, the difference is probably negligible and you should use what you understand better. – For large arrays, use Instruments, profile and compare. Commented Sep 19, 2016 at 12:01
  • 2
    When it comes to performance questions, the answer always is: what did you measure? Commented Sep 19, 2016 at 12:14
  • Thanks for the feedback. Commented Sep 19, 2016 at 12:24

1 Answer 1

1

For unsorted arrays here most simple efficient way (result equal to your first solution):

var sections: [SubMenu]

var selectedItem: BeverageItem? {
    for section in sections.reverse() {// remove .reverse() if you don't really need last existed section
        for beverage in section.beverages {
            if beverage.isSelected {
                return beverage
            }
        }
    }
    return nil
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.