I have two functions they are:
extension Array where Element: Hashable { func uniqueOrderly() -> [Element] { let startTime = CFAbsoluteTimeGetCurrent() var set = Set<Element>() var array = [Element]() for element in self { if set.contains(element) { continue } set.insert(element) array.append(element) } let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime print("Time for uniqueOrderly: \(timeElapsed)") return array } } And second one:
public extension Sequence where Element: Equatable { func unique() -> [Element] { let startTime = CFAbsoluteTimeGetCurrent() var unique: [Element] { return reduce(into: []) { unique, x in if !unique.contains(x) { unique.append(x) } } } let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime print("Time for unique: \(timeElapsed)") return unique } } And I am doing function execution time measurement on the array.
That is :
let arrayToFilter = [1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1,1,2,4,6,1,2,5,7,9,3,3,1] Actual function calls and results are in this order:
arrayToFilter.unique() //Time for unique: 0.00012195110321044922 arrayToFilter.uniqueOrderly() Time for uniqueOrderly: 0.02329099178314209 But when I change order of the function calls my unique() function show horrible time measurements.
arrayToFilter.uniqueOrderly() //Time for uniqueOrderly: 0.0013059377670288086 arrayToFilter.unique() //Time for unique: 8.940696716308594e-06 So my question issue why do I have such situation with different function call order? Additionally when I run these tests in for loop, measurements are quite different. (Aproximatly +- 1 sec)
All mesurants were done in playground and real iOS application with Release build setting (on emulator).
Test Spec:
Xcode Version 10.1
Swift 4.2