开发者

Is using an arraylist of chars faster for performing multiple string concatenation?

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 buil开发者_开发百科d 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.


No, don't use an ArrayList of char 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 most Append operations don't need to "resize" the array.)

That's similar to how StringBuilder works anyway. (It's even closer to how Java's StringBuilder 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.


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:

string[] parts = new string[1000];
for (int i = 0; i < parts.Length; i++) {
  string part = String.Empty;
  for (int j=0; j < 100; j++) {
    part += "*";
  }
  parts[i] = part;
}
string result = String.Concat(parts);

Is about 450 times faster than this code:

string result = string.Empty;
for (int i = 0; i < 100000; i++) {
  result += "*";
}

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%.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜