ur3*_*r3k 3 performance nsdateformatter ios swift
我在iOS应用程序中遇到一些性能问题,同时将2013-12-19 00:00:00.000000格式化的日期转换为中等样式日期(Dec 25, 2014)和双倍值(epoch).根据Xcode分析器,执行此过程的两个函数(下图)占用了大约60%的执行时间
我想知道如何改进此代码,或者是否有更有效的方法来获得我需要的东西.
static func getMediumDate(dateString: String) -> (NSString)? {
// Get the: yyyy-MM-dd
let shorDate = dateString[dateString.startIndex..<dateString.startIndex.advancedBy(10)]
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd"
let stringFormatter = NSDateFormatter()
stringFormatter.locale = NSLocale(localeIdentifier: "en_US")
stringFormatter.dateFormat = "yyyy-MM-dd"
stringFormatter.dateStyle = .MediumStyle
let newDate = dateFormatter.dateFromString(shorDate)
if (newDate != nil){
return stringFormatter.stringFromDate(newDate!)
}else{
return nil
}
}
static func getSortDate(dateString:String) -> Double{
// Get the: yyyy-MM-dd
let shorDate = dateString[dateString.startIndex..<dateString.startIndex.advancedBy(10)]
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd"
let newDate = dateFormatter.dateFromString(shorDate)
let value = newDate?.timeIntervalSince1970
if value < DBL_MIN{
return 0
}else if value > DBL_MAX{
return DBL_MAX
}else if value != nil{
return value!
}else{
return 0
}
}
Run Code Online (Sandbox Code Playgroud)
NSDateFormatter是出了名的慢.您应该创建一次,缓存它并重用相同的实例,而不是每次都创建一个新实例.
例如,您可以执行以下操作:
extension NSDateFormatter {
private static let standardDateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
}
Run Code Online (Sandbox Code Playgroud)
创建NSDateFormatter实例 - 是一项复杂的CPU消费任务。
最好使用一次或创建共享实例。
看看这个描述最佳NSDateFormatter实践的线程- Swift 中 NSDateFormatter 的最佳实践是什么?
关于这方面的更多信息,您可以在Apple 的数据格式指南中找到:
高速缓存格式化程序以提高效率
创建日期格式化程序并不是一项廉价的操作。如果您可能经常使用格式化程序,那么缓存单个实例通常比创建和处理多个实例更有效。一种方法是使用静态变量。
因此,要重构您的代码 - 您应该用初始化NSDataFormatter并仅返回 1 个共享实例(1 个内存地址)的函数替换 3 个实例的初始化,然后使用返回的实例。
| 归档时间: |
|
| 查看次数: |
1343 次 |
| 最近记录: |