Created
February 5, 2018 06:14
-
-
Save yossan/34cd72d5de6d33b2332d704d3d07e650 to your computer and use it in GitHub Desktop.
Calculation speed comparing a for-statement with a KVC operation
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 Foundation | |
class Value: NSObject { | |
@objc let raw: Int | |
init(_ raw: Int) { | |
self.raw = raw | |
} | |
override var description: String { | |
return "\(self.raw)" | |
} | |
} | |
class Collection: NSObject { | |
@objc var values: [Value] | |
override init() { | |
self.values = [] | |
super.init() | |
} | |
override var description: String { | |
return "vals: \(self.values)" | |
} | |
} | |
func makeCollection() -> Collection { | |
return Array(0..<100000).map(Value.init).reduce(into: Collection()) { acc, val in | |
let temp = acc | |
temp.values.append(val) | |
} | |
} | |
@discardableResult | |
func testKVC() -> Float { | |
let col = makeCollection() | |
let avg = col.value(forKeyPath: "[email protected]") as! Float | |
return avg | |
} | |
@discardableResult | |
func testForStatement() -> Float { | |
let col = makeCollection() | |
var sum: Int = 0 | |
for val in col.values { | |
sum += val.raw | |
} | |
return Float(sum) / Float(col.values.count) | |
} | |
@discardableResult | |
func testReduce() -> Float { | |
let col = makeCollection() | |
let sum = col.values.reduce(0) { acc, value in | |
return acc + value.raw | |
} | |
return Float(sum) / Float(col.values.count) | |
} | |
func calculateTime(exec: ()->()) { | |
let start = CFAbsoluteTimeGetCurrent() | |
exec() | |
let end = CFAbsoluteTimeGetCurrent() | |
print("calculation time: \(end - start)") | |
} | |
calculateTime { | |
let r = testKVC() //0.59 | |
print(r) | |
} | |
calculateTime { | |
let r = testForStatement() //0.167 | |
print(r) | |
} | |
calculateTime { | |
let r = testReduce() //0.167 | |
print(r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment