Skip to content

Instantly share code, notes, and snippets.

@AvdLee
Created October 4, 2018 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AvdLee/31f52bf77ddccf8c02defbd727366eba to your computer and use it in GitHub Desktop.
Save AvdLee/31f52bf77ddccf8c02defbd727366eba to your computer and use it in GitHub Desktop.
For each vs for loop performance
//: Playground - noun: a place where people can play
import XCTest
class MyTests: XCTestCase {
lazy var testData: [Int] = {
return (0..<1000).map { Int($0) }
}()
func testForLoop() {
measure {
var evenNumbers: [Int] = []
for number in testData {
if number % 2 == 0 {
evenNumbers.append(number)
}
}
}
}
func testForEachLoop() {
measure {
var evenNumbers: [Int] = []
testData.filter { number in number % 2 == 0}.forEach { evenNumbers.append($0) }
}
}
}
MyTests.defaultTestSuite.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment