解析日期时的性能问题

Performance issues while parsing dates

我的 iOS 应用程序在将 2013-12-19 00:00:00.000000 格式的日期转换为中型日期 (Dec 25, 2014) 和双精度值(纪元)时遇到一些性能问题.根据 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
    }()
}

创建 NSDateFormatter 实例 - 是一项复杂的 CPU 消耗任务。
最好使用一次或创建共享实例。

看看这个描述最佳 NSDateFormatter 实践的帖子 -

您还可以在 Data Formatting Guide 中找到来自 Apple 的更多信息:

Cache Formatters for Efficiency

Creating a date formatter is not a cheap operation. If you are likely to use a formatter frequently, it is typically more efficient to cache a single instance than to create and dispose of multiple instances. One approach is to use a static variable.

因此,要重构您的代码 - 您应该将 3 个 NSDataFormatter 实例的初始化替换为初始化和 returns 只有 1 个共享实例(1 个内存地址)的函数,然后使用返回的实例。