Swift ios 性能优化之 DateFormate Time 耗时 对比

71 阅读1分钟

Swift ios 性能优化之 DateFormate CPU使用 对比

Swift ios 性能优化之 DateFormate Time 耗时 对比

为什么要优化NSDateFormatter?

首先,过度的创建NSDateFormatter用于NSDateNSString之间转换,会导致App卡顿,打开Profile工具查一下性能,你会发现这种操作占CPU比例是非常高的。据官方说法,创建NSDateFormatter代价是比较高的,如果你使用的非常频繁,那么建议你缓存起来,缓存NSDateFormatter一定能提高效率。

万次 字符串转 Int ,和 万次DateFormate 时间转化对比

//
//  DateFormateMoreController.swift
//  DateFormatTest
//
//  Created by LiZhi on 2024/8/6.
//


import UIKit

class DateFormateMoreController: UIViewController {

    override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor.lightText

        self.title = "多个"

        let button = UIButton(frame: CGRect(x: 20, y: 100, width: 280, height: 60))
        button.setTitle("请点击测试DateFormate", for: .normal)

        button.backgroundColor = UIColor.red

        button.addTarget(self, action: #selector(buttonMore1Click), for: .touchUpInside)

        self.view.addSubview(button)

        let button2 = UIButton(frame: CGRect(x: 20, y: 200, width: 180, height: 60))

        button2.setTitle("String 转 int", for: .normal)

        button2.backgroundColor = UIColor.red

        button2.addTarget(self, action: #selector(buttonMore2Click), for: .touchUpInside)

        self.view.addSubview(button2)
    }

    @objc func buttonMore1Click(){
        for i in 0...10000 {
            changeDate()
        }
    }

    
    @objc func buttonMore2Click(){
        for i in 0...10000 {
            stringToInt()
        }
    }

 
    func changeDate(){
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let date:Date? = dateFormatter.date(from: "2024-08-06")
    }


    func stringToInt(){
        let str: String = "123"
        let it: Int? = Int(str)
    }
}
1.万次 string 转int 耗时 1ms (buttonMore2Click)

image.png

2.万次DateFormate 时间转化 耗时 1.65s (buttonMore1Click)

image.png

1ms 和 1.65s 相差还是很大的

3.万次DateFormate 时间转化,最耗时操作 是 dateFormatter.date(from: "2024-08-06")

image.png

参考 juejin.cn/post/684490…