Skip to content

Instantly share code, notes, and snippets.

@airspeedswift
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save airspeedswift/5e2944cec6a823d1fbd0 to your computer and use it in GitHub Desktop.

Select an option

Save airspeedswift/5e2944cec6a823d1fbd0 to your computer and use it in GitHub Desktop.
AnyObject.property is slower than ActualClass.property
import Foundation
@objc class MyClass: NSObject {
var someProperty: Int
init(_ x: Int) { someProperty = x }
}
let classes: [AnyObject] = (0..<10_000).map { _ in MyClass(Int(arc4random())) }
func timeRun<T>(name: String, f: ()->T) -> String {
let start = CFAbsoluteTimeGetCurrent()
let result = f()
let end = CFAbsoluteTimeGetCurrent()
let timeStr = toString(Int((end - start) * 1_000_000))
return "\(name)\t\(timeStr)µs, produced \(result)"
}
let runs = [
("Using AnyObj.someProperty", {
reduce(classes, 0) { prev,next in max(prev,next.someProperty) }
}),
("Using MyClass.someProperty", {
reduce(classes, 0) { prev,next in
(next as? MyClass).map { max(prev,$0.someProperty) } ?? prev
}
}),
("Using plain ol' for loop", {
var maxSoFar = 0
for obj in classes {
if let mc = obj as? MyClass {
maxSoFar = max(maxSoFar, mc.someProperty)
}
}
return maxSoFar
}),
]
println("\n".join(map(runs, timeRun)))
With optimization: (swiftc -O AnyObjVs.swift)
Using AnyObj.someProperty 3365µs, produced 4294759641
Using MyClass.someProperty 1189µs, produced 4294759641
Using plain ol' for loop 1197µs, produced 4294759641
Without: (swiftc -Onone AnyObjVs.swift)
Using AnyObj.someProperty 10944µs, produced 4294758501
Using MyClass.someProperty 13944µs, produced 4294758501
Using plain ol' for loop 8189µs, produced 4294758501
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment