Avatar
@swift-5.3.3 -O import Foundation func measure(_ body: () -> Void) { let start = Date.timeIntervalSinceReferenceDate for _ in 0 ..< 10 { body() } let end = Date.timeIntervalSinceReferenceDate print((end - start) / 10) } func mapFilter(_ n: Int) -> [Int] { precondition(n >= 1) return (1 ... n).map { $0 * $0 }.filter { $0 % 7 == 1 } } func lazyMapFilter(_ n: Int) -> [Int] { precondition(n >= 1) return Array((1 ... n).lazy.map { $0 * $0 }.filter { $0 % 7 == 1 }) } func mapFilterByLoop(_ n: Int) -> [Int] { precondition(n >= 1) var result: [Int] = [] for i in 1 ... n { let square = i * i guard square % 7 == 1 else { continue } result.append(square) } return result } let n: Int = 10_000_000 + (1 ... 100).randomElement()! var a = 0 measure { a += mapFilter(n).count } measure { a += lazyMapFilter(n).count } measure { a += mapFilterByLoop(n).count } print(a)