使用字符数组列表执行多个字符串连接是否更快?
我正在使用 .Net 微框架,因此 StringBuilder 不可用。
我看到一些来自专业人士的代码使用字符数组列表来连接和构建字符串,而不是 + 运算符。他们本质上构建了一个托管代码 StringBuilder。
这有性能优势吗?假设串联次数大于 10,并且字符串长度也大于 10。
I'm using the .Net micro framework so the StringBuilder is not available.
I have seen some code from apt professionals to use an Arraylist of chars to concat and build strings, as opposed to the + operator. They essentially build a managed code StringBuilder.
Is there a performance advantage to this? Assume the number of concatenations are higher than 10 and string lengths are also larger than 10.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不要使用
char
值的ArrayList
。这将限制每个字符 - 性能将非常糟糕,内存使用情况也是如此。 (引用的大小 + 每个字符的盒装字符的大小...哎呀!)在内部使用
char[]
并“调整”它的大小(创建一个新数组并将内容复制到其中)你需要,也许每次都加倍大小。 (编辑:您不会将其大小调整为您需要的确切大小 - 您将从 16 个字符开始,然后不断加倍 - 因此大多数Append
操作不会 需要“调整”数组的大小。)这与
StringBuilder
的工作方式类似。 (它甚至更接近 Java 的StringBuilder
的工作方式。)我建议您使用最重要的成员实际构建自己的
StringBuilder
类型。对其进行单元测试,并在适当的情况下进行分析。如果您想要一个简短的示例,请告诉我。
No, don't use an
ArrayList
ofchar
values. That will box every char - performance will be horrible, as will memory usage. (Size of a reference + size of a boxed char for each character... yikes!)Use a
char[]
internally and "resize" it (create a new array and copy the contents in) when you need to, perhaps doubling in size each time. (EDIT: You don't resize it to the exact size you need - you would start off with, say, 16 chars and keep doubling - so mostAppend
operations don't need to "resize" the array.)That's similar to how
StringBuilder
works anyway. (It's even closer to how Java'sStringBuilder
works.)I suggest you actually build your own
StringBuilder
type with the most important members. Unit test the heck out of it, and profile where appropriate.Let me know if you want a short example.
使用字符 ArrayList 构建字符串被认为高性能的唯一原因是,如果将其与性能非常糟糕的东西进行比较。使用 += 连接一个巨大的字符串就是一个性能如此糟糕的例子。
如果您只是连接成几个较短的字符串而不是一个大字符串,则可以使字符串连接更加高效。
例如,以下代码:
比以下代码快大约 450 倍:
StringBuilder 仍然更快,但仅比第一个示例快四倍左右。因此,通过使用较短的字符串,您可以将时间减少 99.78%,而使用 StringBuilder 只会再减少 0.16%。
The only reason that using an ArrayList of chars to build a string would be considered performant is if you compare it to something that has really bad performance. Concatenating a huge string using += would be an example of something that would have such bad performance.
You can make the string concatenation a lot more efficient if you just concatenate into several shorter strings instead of one large string.
This code, for example:
Is about 450 times faster than this code:
A StringBuilder is still faster, but it's only about four times faster than the first example. So by using shorter strings you can cut the time by 99.78%, and using a StringBuilder would only cut another 0.16%.