Skip to content

Instantly share code, notes, and snippets.

@JoshuaSullivan
Last active April 8, 2019 18:33
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save JoshuaSullivan/6c0d0134e66c60c6cd8c to your computer and use it in GitHub Desktop.
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