性能优化之 DateFormate Swift ios
参考 帖子 www.cnblogs.com/tingxins/p/…
DateFormate 耗时 参考帖子:juejin.cn/post/684490…
为什么要优化NSDateFormatter?
首先,过度的创建NSDateFormatter用于NSDate与NSString之间转换,会导致App卡顿,打开Profile工具查一下性能,你会发现这种操作占CPU比例是非常高的。据官方说法,创建NSDateFormatter代价是比较高的,如果你使用的非常频繁,那么建议你缓存起来,缓存NSDateFormatter一定能提高效率。
之前一直听说 ios 性能优化时, DateFormate 开销过大,需要缓存起来。今天我就来测试一下DateFormate, 验证一下
测试手机: iphone 6s plus
测试系统:ios 13
一万次 string 转 Int 的cpu 如下
@objc func button2Click(){
for i in 0...10000 {
stringToInt()
}
}
func stringToInt(){
let str: String = "123"
let it: Int? = Int(str)
}
一万次的 dateformate string 转 Date
@objc func buttonClick(){
for i in 0...10000 {
changeDate()
}
}
func changeDate(){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date:Date? = dateFormatter.date(from: "2024-08-06")
}
确实cpu 的使用率太高啦。
接下来试下 把 DateFormate 缓存起来
class DateFormateOnceController: UIViewController {
let dateFormatter = DateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
print("--- dateFormatter = ",dateFormatter)
self.view.backgroundColor = UIColor.yellow
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(buttonOne1Click), for: .touchUpInside)
self.view.addSubview(button)
}
@objc func buttonOne1Click(){
for i in 0...10000 {
changeDate()
}
}
func changeDate(){
self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date:Date? = self.dateFormatter.date(from: "2024-08-06")
}
}
稍微降了一些
对比DateFormat 各个步骤 占据的cpu
万次 DateFormatter 初始化
///仅初始化
@objc func buttonOne2Click(){
for i in 0...10000 {
let dateFormatter2 = DateFormatter()
}
}
万次 格式设置
@objc func buttonOne3Click(){
for i in 0...10000 {
self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
}
}
万次 转化
@objc func buttonOne4Click(){
for i in 0...10000 {
let date:Date? = self.dateFormatter.date(from: "2024-08-06")
}
}
总结对比(非精确值)
| 过程 | CPU(%) | 相对97占比 |
|---|---|---|
| 重复初始化DateFormate 转换时间 | 97 | 100 |
| string转数字 | 5 | 5 |
| 统一DateFormate 转换时间 | 85 | 87 |
| 单DateFormate 初始化 | 4 | 4 |
| 单DateFormate 格式设置 | 4 | 4 |
| 单DateFormate 转化 | 57 | 58 |
DateFormate 最耗时的方法是 date转化(let date:Date? = self.dateFormatter.date(from: "2024-08-06"));约占总时间的 87% (57 ÷ (57+4+4));
把DateFormate 缓存 起来节省的cpu 是 13%(100-87)。
测试代码地址:github.com/lizhi0123/L…