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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With