I have a code like this:
string str = "";
for(int i=0; i<100000; i++){
...........
str += ...;
}
return str;
but, this code is very slow, and when execute, it takes 7 minutes.
Do you think a solution would be?
I have a code like this:
string str = "";
for(int i=0; i<100000; i++){
...........
str += ...;
}
return str;
but, this code is very slow, and when execute, it takes 7 minutes.
Do you think a solution would be?
The benefits of StringBuilder should be perfect useful with huge strings.
In your example, every time you concatenate a string (str += ....
) you create a new string object, and it becomes longer, the more time execution is needed to copy from the old string to the new string.
Here is a demonstration how it works at memory
level.
StringBuilder
actions different. It was included exactly for this type of problem. So, .NET Framework
includes StringBuilder
class which is optimized for string concatenation
.
So StringBuilder
should perform better in your situation.