NSMutableString的-appendString:方法是一种建立一个大字符串的有效方法吗? [英] Is NSMutableString's -appendString: method an efficient way to build up a large string?

查看:105
本文介绍了NSMutableString的-appendString:方法是一种建立一个大字符串的有效方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我计划通过迭代一个集合并一次生成一个块来构建一个潜在的大字符串。如果我只是从一个NSMutableString开始,并重复附加块,它的工作合理有效,或者是一个 Schlemiel的画家情况?对我来说似乎是可行的,NSMutableString是以避免这种方式实现的,但我在官方文档中找不到任何讨论,我想确定。

I'm planning on building up a potentially large string by iterating over a collection and generating chunks at a time. If I were to simply start with an NSMutableString and repeatedly append chunks to it, does that work reasonably efficiently or is it a Schlemiel the Painter situation? It seems plausible to me that NSMutableString is implemented in a way that avoids this, but I can't find any discussion of this in the official documentation and I'd like to be sure.

(现在我写这个,我意识到,在这种情况下,我可以建立一个字符串的NSArray和使用-componentsJoinedByString:很容易,但这将是很好知道反正。)

(Now that I'm writing this out, I realize that in this case I can build up an NSArray of strings and use -componentsJoinedByString: just as easily, but this would be good to know anyway.)

推荐答案

Schlemiel情况本身并不发生,因为所有内部NS / CFString表示使用显式长度,像所有合理的字符串实现。 (来自OS X 10.6.2的基本CoreFoundation类型的源的一个稍微修改的版本可用这里。)真正的问题是关于分配开销。

The Schlemiel situation per se does not occur, since all internal NS/CFString representations use an explicit length, like all sane string implementations. (A somewhat modified version of the source of the basic CoreFoundation types from OS X 10.6.2 is available here.) The real question is about allocation overhead.

在发布的代码中,可变字符串的缓冲区一次增长50% (至少 ULONG_MAX / 3UL ),在实际情况下对重分配给出O(log n)绑定。使用 NSArray 方法应该导致单个分配。另一方面,如果你分段构建字符串并在你走的时候释放这些片段,你可能会得到更少的缓存/虚拟机抖动。

In the posted code, mutable strings’ buffers grow by 50 % at a time unless they’re very large (at least ULONG_MAX / 3UL), giving an O(log n) bound on reallocations for practical scenarios. Using the NSArray approach should result in a single allocation. On the other hand, if you build the string piecewise and release the pieces while you go, you might get less cache/VM thrashing.

因此,基本上,优化适用:如果基准测试显示有问题(在大而实际的数据集上),请尝试这两种方法。

So basically, the golden rule of optimization applies: if benchmarking shows a problem (on a large but realistic data set), try both.

这篇关于NSMutableString的-appendString:方法是一种建立一个大字符串的有效方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆