0

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?

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
asady
  • 57
  • 4
  • 4
    seems like space allocation. Could you try the same with a stringbuilder and see if you get an increase in performance? Could also be the actions you didn't mention (in the .........) – Dieter B Jan 19 '18 at 11:59
  • 4
    Because each time you add string to string it makes a new string and shuffles all the memory about. – BugFinder Jan 19 '18 at 11:59
  • It's an O(N^2) operation, so no wonder it's slow. – Matthew Watson Jan 19 '18 at 12:01
  • 1
    Maybe your `...........` is the problem. But in general use a `StringBuilder` – Tim Schmelter Jan 19 '18 at 12:02
  • 1
    What else is there in your code in the place of `.....`? – Bharadwaj Jan 19 '18 at 12:02
  • 2
    https://blog.codinghorror.com/the-sad-tragedy-of-micro-optimization-theater/ – Fildor Jan 19 '18 at 12:02
  • 1
    @Fildor Thank you for that link. Time to add that to my lovely collection already containing gems like _Bobby Tables_ and _Parse HTML With Regex_. – Nyerguds Jan 19 '18 at 12:11
  • I found a solution :) inside the loop, use List instead of string. List lst= new List(); for(int i=0; i<100000; i++){ ........... lst.Add(...); } return String.Join("", lst.ToArray());; it is very very fast. – asady Jan 19 '18 at 12:11
  • 1
    @asadynet Really, just use `StringBuilder`. It's what it's for. `String.Join` is specifically for adding separators between the strings. – Nyerguds Jan 19 '18 at 12:12

1 Answers1

3

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.

enter image description here

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.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128