Last active
June 9, 2021 14:35
-
-
Save ppeelen/4a02719f024c2d34464d618ff3a15fdb to your computer and use it in GitHub Desktop.
Swift: Lazy filter with prefix. Check if occurrence of X happens more than Y times using filter
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
struct FooBar { | |
let state: Bool | |
func isTrue() -> Bool { state } // Called 1000 times | |
func isFalse() -> Bool { !state } // Called 92 times | |
} | |
let fooList = (0..<1000).compactMap { n in FooBar(state: Bool.random()) } | |
let start = CFAbsoluteTimeGetCurrent() | |
if fooList.filter({ $0.isTrue() }).count > 1 { | |
print("> 1") | |
} else { | |
print("<= 1") | |
} | |
let diff = CFAbsoluteTimeGetCurrent() - start | |
debugPrint("First one took: \(diff)") // 0.02408897876739502 | |
let secondStart = CFAbsoluteTimeGetCurrent() | |
if fooList.lazy.filter({ $0.isFalse() }).prefix(20).count > 1 { | |
print("> 1") | |
} else { | |
print("<= 1") | |
} | |
let diff2 = CFAbsoluteTimeGetCurrent() - secondStart | |
debugPrint("Second one took: \(diff2)") // Took 0.0023419857025146484 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment