Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
stckvrflw Avatar asked Nov 17 '09 11:11

stckvrflw


2 Answers

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.

like image 197
Kobi Avatar answered Oct 21 '22 17:10

Kobi


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();
like image 30
bruno conde Avatar answered Oct 21 '22 17:10

bruno conde