开发者

C# += (plus equals) (Assignment by addition) working very slow, when string is too long?

I have a for loop and what I do is this.

forloop ( loop 7000 times)
{
x += 2000_char_long_string;
}

Code lasts really long time开发者_开发知识库 in this forloop, maybe more than 1 minute. How can I solve this problem?

Thanks.


Use a StringBuilder.

StringBuilder sb = new StringBuilder();
for(int i=0; i< 200; i++){
   sb.append(longString);
}
return sb.ToString();

When you use += on strings, you keep creating new strings, and keep locating larger and larger blocks of memory. That is why the operation is so slow.


Using a StringBuilder, as @Kobi referenced you can still increase performance by initializing it. It seems you can determine the final size of the string in advance.

StringBuilder sb = new StringBuilder(7000*2000);
for(int i=0; i< 7000; i++){
   sb.append(2000_char_long_string);
}
return sb.ToString();


String manipulations are immutable. There will be a new string created everytime the stmt x += 2000_char_long_string; is executed. Hence as suggested by Kobi, you should use a StringBuilder class.

However, in your case, you should specify the capacity in the StringBuilder constructor.

This is because, if not specified, the default capacity of StringBuilder during creation is 16.

Once this capacity is exhausted, it will create a new contiguous memory location, copy all the contents of the StringBuilder to the new location and point the instance to the new location. Since you are already aware of the approximate size the final string would be (maybe 7000 * 2000), you can specify the capacity accordingly.

Please see my answer to StringBuilder and capacity? for more details.


You should use the StringBuilder class


C# string object is immutable, every time the contents are changed new object is created and the new contents are copied. Use StringBuilder instead, it's provided to address the issue that you are facing

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜