首页 > 解决方案 > 为什么相同的代码在 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);
}

我很想知道是什么导致了性能差异。

标签: objective-cperformance

解决方案


推荐阅读