gpt4 book ai didi

ios - 解析日期时的性能问题

转载 作者:搜寻专家 更新时间:2023-10-31 21:53:10 28 4
gpt4 key购买 nike

在将 2013-12-19 00:00:00.000000 格式的日期转换为中型日期 (Dec 25, 2014) 和 double 值(纪元)。根据 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
}
}

最佳答案

NSDateFormatter 是出了名的慢。您应该创建一次,缓存它并重用同一个实例,而不是每次都创建一个新实例。

例如,您可以执行以下操作:

extension NSDateFormatter {
private static let standardDateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter
}()
}

关于ios - 解析日期时的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574569/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com