gpt4 book ai didi

ios - 为什么 UIFont(描述符 :size:) is x200 slower than UIFont(name:size:)?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:25:12 25 4
gpt4 key购买 nike

最近我注意到滚动的性能正在减慢。我追踪了问题,发现原因是使用了 UIFont(descriptor:size:) 创建的字体。构造函数。我更改了 UIFont(name:size:) 的构造函数我的问题都解决了。

我在 project 中隔离了问题.代码是:

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var firstLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!

@IBAction func onStartTest(sender: AnyObject) {
startMeasurement()
let firstFont = UIFont(name: "Marker Felt", size: 16)
firstLabel.font = firstFont
finishMeasurement("UIFont(name)")

startMeasurement()
let secondFontDescriptor = UIFontDescriptor(name: "Marker Felt", size: 16)
let secondFont = UIFont(descriptor: secondFontDescriptor, size: 16)
secondLabel.font = secondFont
finishMeasurement("UIFont(descriptor)")
}
}

private var time: UInt64 = 0

public func startMeasurement() {
time = mach_absolute_time()
}

public func finishMeasurement(name: String) {
let duration = mach_absolute_time() - time
print("* \(name) \(duration)ns")
}

这些是我的一些测量结果:

iPhone 4S - iOS 9.0.2

* UIFont(name) 111,300ns
* UIFont(descriptor) 112,420,263ns

iPhone 6S - iOS iOS 9.2

* UIFont(name) 134,247ns
* UIFont(descriptor) 17,047,707ns

Simulator - iOS 9.2

* UIFont(name) 1,971,106ns
* UIFont(descriptor) 485,208,205ns

Simulator - iOS 8.1

* UIFont(name) 9,946,584ns
* UIFont(descriptor) 1,957,802,431ns

我做错了什么吗?

最佳答案

我在 WWDC 2018 上问了一位工程师,他基本上是这样告诉我的:

描述符非常非常昂贵,因为它们每次都在整个系统字体库中搜索您提供的特征。他告诉我这个搜索确实没有优化,所以永远不应该在滚动情况下使用,应该只调用一次然后缓存。这样做是因为您实际上不需要指定字体名称,而只需指定字体的各种特性,系统就会为您提供一些东西。

UIFont(name: size:) 但是速度非常快,因为它直接转到系统中请求的字体。它知道字体在哪里,因为你已经给出了完整的确切名称,然后它可以缩放它。没有其他好的功能。

这大致是一个 O(n) 操作与一个 O(1)

关于ios - 为什么 UIFont(描述符 :size:) is x200 slower than UIFont(name:size:)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34954956/

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