objective-c - 为什么相同的代码在 viewDidLoad 和延迟任务中的性能会相差 3 倍
问题描述
我在iPhone7 iOS13上测试TextKit的布局性能,但我发现同样的代码有不同的性能。
测试代码如下,viewDidLoad测试方法耗时分别为0.305ms、0.082ms、0.062ms,延迟任务耗时1.018ms、0.425ms、0.462ms。
我在测试方法中减少了代码,这个问题依然存在,这个问题与TextKit无关。
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.title = @"Demo";
self.navigationController.navigationBar.tintColor = [UIColor blackColor];
[self test];
[self test];
[self test];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// Each test call takes more than 3 times more time than the test call in viewDidLoad
[self test];
[self test];
[self test];
});
}
- (void)test
{
NSTimeInterval startTime = [[NSDate new] timeIntervalSinceReferenceDate];
NSTextContainer* textContainer = [[NSTextContainer alloc] init];
textContainer.exclusionPaths = @[];
NSLayoutManager * layoutManager = [NSLayoutManager new];
layoutManager.allowsNonContiguousLayout = false;
layoutManager.hyphenationFactor = 0;
layoutManager.showsInvisibleCharacters = false;
layoutManager.showsControlCharacters = false;
layoutManager.usesFontLeading = true;
[layoutManager addTextContainer:textContainer];
NSTextStorage* textStorage = [[NSTextStorage alloc] initWithString:@"h"];
[textStorage addLayoutManager:layoutManager];
NSTimeInterval endTime = [[NSDate new] timeIntervalSinceReferenceDate];
NSLog(@"Test generate cost in %f ms", (endTime - startTime) * 1000.0);
}
我很想知道是什么导致了性能差异。
解决方案
推荐阅读
- spring-boot - Spring OAuth2 ClientDetailsServiceConfigurer 可以通过数据库进行身份验证吗?
- corda - FungibleAsset 是否与 Java CorDapps 兼容?
- mysql - (async) 使用 sequelize 和 node 在 mysql 数据库中创建多个寄存器
- excel - 是否可以使用 maatwebsite 修改现有的 excel 文件?
- python - ValueError:无法将字符串转换为浮点数 - kmeans(熊猫)
- sql - 我可以在一个查询中选择 2 列上的 DISTINCT 并按 1 列分组的总和吗?
- node.js - Firestore 查询有时不包含更新的数据
- reactjs - 如何在 reactjs 中将道具传递给另一个组件
- python - 在生成无限数据时,PyTorch 的 __len__ 应该是什么?
- java - 试图捕捉特定的 ConstraintViolationException