Skip to content

Commit 19d8965

Browse files
authored
Array.sorted(like:keyPath:) performance improvement (#1226)
Using a Dictionary(uniqueKeysWithValues:) is more efficient than reduce(into:). I used time profile and found a significant improvement.
1 parent c4571a9 commit 19d8965

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

Sources/SwifterSwift/SwiftStdlib/ArrayExtensions.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ public extension Array {
5858
/// - keyPath: keyPath indicating the property that the array should be sorted by
5959
/// - Returns: sorted array.
6060
func sorted<T: Hashable>(like otherArray: [T], keyPath: KeyPath<Element, T>) -> [Element] {
61-
let dict = otherArray.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset }
61+
let dict = Dictionary(uniqueKeysWithValues: otherArray.enumerated().map { ($1, $0) })
6262
return sorted {
6363
guard let thisIndex = dict[$0[keyPath: keyPath]] else { return false }
6464
guard let otherIndex = dict[$1[keyPath: keyPath]] else { return true }

0 commit comments

Comments
 (0)