Skip to content

Instantly share code, notes, and snippets.

@r-plus
Created January 20, 2016 18:02
Show Gist options
  • Select an option

  • Save r-plus/d1fbf96a31dcc0f308a8 to your computer and use it in GitHub Desktop.

Select an option

Save r-plus/d1fbf96a31dcc0f308a8 to your computer and use it in GitHub Desktop.
faster getting way than filter+first.
import CoreFoundation
extension Array {
func firstMatchFilter<T: Equatable>(target: T) -> Element? {
let start = CFAbsoluteTimeGetCurrent()
guard let index = self.indexOf({ $0 as! T == target }) else {
return nil
}
let end = CFAbsoluteTimeGetCurrent()
print("elapsed time = \(end - start)")
return self[index]
}
func firstMatchFilter(@noescape predicate: (Element) throws -> Bool) rethrows -> Element? {
let start = CFAbsoluteTimeGetCurrent()
guard let index = try self.indexOf(predicate) else {
return nil
}
let end = CFAbsoluteTimeGetCurrent()
print("elapsed time = \(end - start)")
return self[index]
}
func filterFirst<T: Equatable>(target: T) -> Element? {
let start = CFAbsoluteTimeGetCurrent()
let result = filter { $0 as! T == target }.first
let end = CFAbsoluteTimeGetCurrent()
print("elapsed time = \(end - start)")
return result
}
}
var array = [Int]()
for i in 0...1000 {
array.append(i)
}
//array.firstMatchFilter(1) // elapsed time : about 1ms
//array.filterFirst(1) // elapsed time : about 300ms
//array.firstMatchFilter(500) // elapsed time : about 150ms
//array.filterFirst(500) // elapsed time : about 300ms
//array.firstMatchFilter(1000) // elapsed time : about 300ms
//array.filterFirst(1000) // elapsed time : about 300ms
array.firstMatchFilter { $0 == 500 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment