objective-c – 在AppKit中测量文本宽度的性能

有没有办法在AppKit中测量大量Nsstring对象的宽度(比如说一百万)真的很快?我尝试了3种不同的方法

> [NSString sizeWithAttributes:]
> [NSAttributedString size]
> NSLayoutManager(获取文本宽度而不是高度)

以下是一些性能指标

Count\Mechanism    sizeWithAttributes    NSAttributedString    NSLayoutManager
1000               0.057                 0.031                 0.007
10000              0.329                 0.325                 0.064
100000             3.06                  3.14                  0.689
1000000            29.5                  31.3                  7.06

NSLayoutManager显然是要走的路,但问题是

由于创建了重量级的NSTextStorage对象,内存占用空间很大(根据分析器大于1GB).
>创作时间高所有时间都是在创建上述字符串的过程中,这是一个破坏者本身(随后测量具有创建和排列的字形的NSTextStorage对象只需要大约0.0002秒).
> 7秒仍然太慢我正在努力做什么.有更快的方法吗?在一秒钟内测量一百万个字符串?

如果你想玩,Here是github项目.

解决方法

这里有一些我还没有尝试的想法.

>直接使用Core Text.其他的API是建立在它之上的.
并行化所有现代Mac(甚至所有现代iOS设备)都有多个内核.将字符串数组分成几个子阵列.对于每个子阵列,将块提交到global GCD queue.在块中,创建必要的Core Text或NSLayoutManager对象并测量子阵列中的字符串.这两种API都可以安全地使用. (Core Text) (NSLayoutManager)
>关于“高内存占用”:Use Local Autorelease Pool Blocks to Reduce Peak Memory Footprint.
>关于“所有的时间都是在创造上述字符串的过程中,这本身就是一个破产者”:你是否一直在这些方面付出代价:

double random = (double)arc4random_uniform(1000) / 1000;
Nsstring *randomNumber = [Nsstring stringWithFormat:@"%f",random];

格式化浮点数是昂贵的.这是你真正的用例吗?如果您只想格式化n / 1000形式的随机有理数为0≤n< 1000,有更快的方法.此外,在许多字体中,所有数字的宽度都相同,因此可以轻松排列数字列.如果您选择这样的字体,您可以避免首先测量字符串.
UPDATE

这是使用Core Text提供的最快的代码.发行版本几乎是Core i7 MacBook Pro上单线程版本的两倍.我的叉项目是here.

static CGFloat maxWidthOfStringsUsingCTFramesetter(NSArray *strings,NSRange range) {
    Nsstring *bigString = [[strings subarrayWithRange:range] componentsJoinedByString:@"\n"];
    NSAttributedString *richText = [[NSAttributedString alloc] initWithString:bigString attributes:@{ NSFontAttributeName: (__bridge NSFont *)font }];
    CGPathRef path = CGPathCreateWithRect(CGRectMake(0,CGFLOAT_MAX,CGFLOAT_MAX),NULL);
    CGFloat width = 0.0;
    CTFramesetterRef setter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)richText);
    CTFrameRef frame = CTFramesetterCreateFrame(setter,CFRangeMake(0,bigString.length),path,NULL);
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
    for (id item in lines) {
        CTLineRef line = (__bridge CTLineRef)item;
        width = MAX(width,CTLineGetTypographicBounds(line,NULL,NULL));
    }
    CFRelease(frame);
    CFRelease(setter);
    CFRelease(path);
    return (CGFloat)width;
}

static void test_CTFramesetter() {
    runTest(__func__,^{
        return maxWidthOfStringsUsingCTFramesetter(testStrings,NSMakeRange(0,testStrings.count));
    });
}

static void test_CTFramesetter_dispatched() {
    runTest(__func__,^{
        dispatch_queue_t gatherQueue = dispatch_queue_create("test_CTFramesetter_dispatched result-gathering queue",nil);
        dispatch_queue_t runQueue = dispatch_get_global_queue(QOS_CLASS_UTILITY,0);
        dispatch_group_t group = dispatch_group_create();

        __block CGFloat gatheredWidth = 0.0;

        const size_t Parallelism = 16;
        const size_t totalCount = testStrings.count;
        // Force unsigned long to get 64-bit math to avoid overflow for large totalCounts.
        for (unsigned long i = 0; i < Parallelism; ++i) {
            NSUInteger start = (totalCount * i) / Parallelism;
            NSUInteger end = (totalCount * (i + 1)) / Parallelism;
            NSRange range = NSMakeRange(start,end - start);
            dispatch_group_async(group,runQueue,^{
                double width = maxWidthOfStringsUsingCTFramesetter(testStrings,range);
                dispatch_sync(gatherQueue,^{
                    gatheredWidth = MAX(gatheredWidth,width);
                });
            });
        }

        dispatch_group_wait(group,disPATCH_TIME_FOREVER);

        return gatheredWidth;
    });
}

相关文章

对象的传值与返回说起函数,就不免要谈谈函数的参数和返回值...
从实现装饰者模式中思考C++指针和引用的选择最近在看...
关于vtordisp知多少?我相信不少人看到这篇文章,多半是来自...
那些陌生的C++关键字学过程序语言的人相信对关键字并...
命令行下的树形打印最近在处理代码分析问题时,需要将代码的...
虚函数与虚继承寻踪封装、继承、多态是面向对象语言的三大特...