iOS提高数组遍历性能的小技巧

利用set提高遍历性能

let members: [Member]
let platinumMemberIDs:[Int]

优化前
时间复杂度是O(n²)

var platinumMembers = members.filter {
    platinumMemberIDs.contains($0.id)
}

优化后
时间复杂度是O(n)

let platinumMemberIDSet = Set(platinumMemberIDs)
var platinumMembers = members.filter {
    platinumMemberIDSet.contains($0.id)
}

利用字典提高遍历性能

let starUsers: [User]
let recentUsers: [User]

优化前
时间复杂度是O(n²)

ar duplicatedUsers = [User]()
for star in starUsers {
  for recent in recentUsers {
    if star.email == recent.email {
      duplicatedUsers.append(star)
    }
  }
}

优化后
时间复杂度是O(n)

let recentUserMap = Dictionary(uniqueKeysWithValues: recentUsers.map { ($0.email, $0) })
let duplicatedUsers = starUsers.filter {
  guard let _ = recentUserMap[$0.email] else { return false }
  return true
}

如何通过减少集合类型初始化来提高iOS代码性能?

使用 reduce(::)reduce(into:_:) 来演示执行速度的差异。这两个示例都旨在创建一个以用户名为键,以用户ID为值的字典

Example 1

let userDict = users.reduce([String: Int]()) { (dict, user) -> [String: Int] in
    var dict = dict
    dict[user.name] = user.id
    return dict
}

Example 2

let userDict2 = users.reduce(into: [:]) { dict, user in
    dict[user.name] = user.id
}

示例1的执行时间为0.07398414611816406秒,而示例2的执行时间为0.0013837814331054688秒。它比示例1快50多倍

参考资料:
https://betterprogramming.pub/how-to-boost-your-ios-code-performance-by-reducing-collection-type-initialisation-564bffee94a3

https://betterprogramming.pub/how-to-boost-your-ios-code-performance-reduce-searching-an-array-55fbdfee2050

你可能感兴趣的:(iOS提高数组遍历性能的小技巧)