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