如何优雅地使用DateFormatter

性能对比

亲,我的简书已不再维护和更新了,所有文章都迁移到了我的个人博客:https://mikefighting.github.io/,欢迎交流。

之所以要聊DateFormatter是因为某次给项目做性能检测,发现创建DateFormatter太消耗性能,我们来做个对比,新建100000个日期。我们使用两种方式:第一种每次创建日期的时候新建一个NSDateFormatter,第二种共用一个NSDateFormatter,来生成日期:

public func testWithMultipleInstantiation() ->CFTimeInterval {
    
        var dateStrings:[String] = []
        dateStrings.reserveCapacity(100000)
        let startTime = CACurrentMediaTime()
        for _ in 0..<100000 {
            let df = DateFormatter()
            df.dateStyle = .medium
            df.timeStyle = .full
            dateStrings.append(df.string(from: Date()))
        }
        let endTime = CACurrentMediaTime()
        return endTime - startTime
    }
    
    public func testWithSingleInstance() ->CFTimeInterval {
    
        var dateStrings: [String] = []
        dateStrings.reserveCapacity(100000)
        let startTime = CACurrentMediaTime()
        let df = DateFormatter()
        df.dateStyle = .medium
        df.timeStyle = .full
        for _ in 0..<100000 {
            dateStrings.append(df.string(from: Date()))   
        }   
        let endTime = CACurrentMediaTime()
        return endTime - startTime
}

然后我们调用这两个方法:

print("testWithMultipleInstantiation--\(testWithMultipleInstantiation())")
print("testWithSingleInstance--\(testWithSingleInstance())")

打印结果是:

testWithMultipleInstantiation--7.83139349098201
testWithSingleInstance--0.742719032976311

从中可以明显看到创建DateFormatter是很消耗性能的,多次创建DateFormatter比单次创建大约要慢11倍。如果我们要用DateFormatter,那么尽量创建一次,然后多次使用。

然后我们再做进一步的实验:创建一次DateFormatter,但是改变这个NSDateFormatter的dateStyletimeStyle

public func testWithSingleInstanceChangeFormatter() ->CFTimeInterval {
        
        var dateStrings: [String] = []
        dateStrings.reserveCapacity(100000)
        let startTime = CACurrentMediaTime()
        let df = DateFormatter()
        for _ in 0..<100000 {
            
            df.dateStyle = .medium
            df.timeStyle = .full
            df.dateStyle = .full
            df.timeStyle = .medium
            dateStrings.append(df.string(from: Date()))
        }
        
        let endTime = CACurrentMediaTime()
        return endTime - startTime
    }

然后调用这个方法:

print("ChangeFormatter--\(testWithSingleInstanceChangeFormatter())")

这时输出的结果是:

ChangeFormatter--5.77827541399165

从中我们可以看到,其对性能的消耗和多次创建DateFormatter相差并不多。最后我们得到这样一个结论:

  1. 每次使用DateFormatter时都新建是最消耗性能的
  2. 创建一个DateFormatter然后改变其dateStyletimeStyle等和1中的性能消耗差不多
  3. 为每一种日期类型创建一种DateFormatter并且不改变其dateStyletimeStyle等属性是性能最优的

解决方案

通过上面的结论,我们发现如果对DateFormatter做成单例,那么就必须保证每个DateFormatter的格式是相同的,因为改变DateFormatter的格式也是很消耗性能的。我们要做多个单例,每种单例是一种formatter,然后分别使用吗?显然太过于麻烦。我们可以使用缓存策略,将每种格式的DateFormatter缓存一份,下次如果有相同格式的Formatter,直接从缓存中取就可以了,这就避免了多次创建和多次改变格式的问题。为了解决这个问题,我使用NSCache做了一个DateFormatter的缓存池:MFDateFormatterPool,已经上传到了GitHub上,分为OC和Swfit两个版本,可以下载并直接使用,如有问题可以联系我。

延伸阅读:

https://www.raywenderlich.com/31166/25-ios-app-performance-tips-tricks#reuseobjects
http://www.chibicode.org/?p=41
https://stackoverflow.com/questions/18195051/crash-in-nsdateformatter-setdateformat-method

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,641评论 25 708
  • 1. 用ARC管理内存 ARC(Automatic ReferenceCounting, 自动引用计数)和iOS5...
    乌七猫阅读 286评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,009评论 19 139
  • 到一个地方旅行,除了看美景,最抓人心的的应该是当地的美食了。 提及美食,往往每一个地方都有一道让人脱口而出的食物名...
    史闪亮阅读 588评论 0 3
  • 一、认识垃圾回收 谈到垃圾回收(Garbage Collection,简称GC),GC中的垃圾,特指存在于内存中的...
    端木轩阅读 281评论 0 1