views:

718

answers:

5

Hello,

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.

+31  A: 

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.

Kobi
+1 Simple as :)
GenericTypeTea
Wow, really fast. :) Thanks.
stckvrflw
An improvement would be to set the initial capacity also. If you're allocating 7000 * 2000 character strings, then set the initial capacity to 14000000 to avoid repeated growing of the buffer.
Greg Beech
+1  A: 

You should use the StringBuilder class

Rafael Mueller
+1  A: 

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

Prashant
I will not forget that, pretty usuful information for me. Thanks.
stckvrflw
+8  A: 

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();
bruno conde
Note that even if you aren't sure what the exact length is, make a best guess. Overguessing doesn't add any overhead (memory aside) and even if you underguess, you'll still allocate less than before.
Blindy
+1  A: 

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.

Rashmi Pandit