Created
January 20, 2016 18:02
-
-
Save r-plus/d1fbf96a31dcc0f308a8 to your computer and use it in GitHub Desktop.
faster getting way than filter+first.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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