Skip to content

Instantly share code, notes, and snippets.

@mattyoung
Created November 26, 2017 19:46
Show Gist options
  • Save mattyoung/25b71da1d414780902cb89b37fedfe3c to your computer and use it in GitHub Desktop.
Save mattyoung/25b71da1d414780902cb89b37fedfe3c to your computer and use it in GitHub Desktop.
import QuartzCore
// make an Int array of random elements
let array = Array((1...2000).map { _ in Int(arc4random_uniform(2000)) } )
let loopCount = 100_000
// closure in a variable
let compareGreater: (Int, Int) -> Bool = { $0 > $1 }
// make sure the two methods produce the same result
assert(array.sorted(by: compareGreater) == array.sorted(by: { $0 > $1 }), "Hey, You! The two are not the same!!!")
// pass closure as a variable
func useVariable() -> Double {
let startTime = CACurrentMediaTime()
for _ in 1...loopCount {
// use a closure store in a variable
_ = array.sorted(by: compareGreater)
}
return CACurrentMediaTime() - startTime
}
// pass closure as a literal
func useLiteral() -> Double {
let startTime = CACurrentMediaTime()
for _ in 1...loopCount {
// use a closure literal
_ = array.sorted(by: { $0 > $1 })
}
return CACurrentMediaTime() - startTime
}
print("Running benchmark...")
var variableTime = 0.0
var literalTime = 0.0
variableTime += useVariable()
literalTime += useLiteral()
literalTime += useLiteral()
variableTime += useVariable()
print("variableTime = \(variableTime)")
print("literalTime = \(literalTime)")
print("variableTime - literalTime = \(variableTime - literalTime)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment