Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Here is some example code that demonstrates the penalty incurred with creating a NSDateFormatter every time you need to format a date instead of creating it once and storing it for use when needed.
import Foundation
import QuartzCore
public func testWithMultipleInstantiation() -> CFTimeInterval {
var dateStrings: [String] = []
dateStrings.reserveCapacity(100000)
let start = CACurrentMediaTime()
for _ in 0..<100000 {
let df = NSDateFormatter()
df.dateStyle = .MediumStyle
df.timeStyle = .MediumStyle
dateStrings.append(df.stringFromDate(NSDate()))
}
let end = CACurrentMediaTime()
return end - start
}
public func testWithSingleInstantiation() -> CFTimeInterval {
var dateStrings: [String] = []
dateStrings.reserveCapacity(100000)
let start = CACurrentMediaTime()
let df = NSDateFormatter()
df.dateStyle = .MediumStyle
df.timeStyle = .MediumStyle
for _ in 0..<100000 {
dateStrings.append(df.stringFromDate(NSDate()))
}
let end = CACurrentMediaTime()
return end - start
}
public func testWithStaticMethod() -> CFTimeInterval {
var dateStrings: [String] = []
dateStrings.reserveCapacity(100000)
let start = CACurrentMediaTime()
for _ in 0..<100000 {
dateStrings.append(NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .MediumStyle))
}
let end = CACurrentMediaTime()
return end - start
}
import Foundation
let timeForMultiple = testWithMultipleInstantiation()
let timeForSingle = testWithSingleInstantiation()
let timeForStatic = testWithStaticMethod()
print("multiple:", timeForMultiple) //multiple: 7.96959602891002
print("single: ", timeForSingle) //single: 0.888885863008909
print("static: ", timeForStatic) //static: 7.89041009696666
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment