.NET String Performance Question

Is it better to use "Example1" in terms of performance? I assume that "Example2" will create a new line on the heap at each iteration, while "Example1" will not ...

Example 1:

StringBuilder letsCount = new StringBuilder("Let count! ");
string sep = ", ";
for(int i=; i< 100; i++)
{
     letsCount.Append(i + sep);
}

Example 2:

StringBuilder letsCount = new StringBuilder("Let count! ");
for(int i=; i< 100; i++)
{
     letsCount.Append(i + ", ");
}
+3
source share
3 answers

The .NET CLR is much smarter than that. These are " interns " string literals, so there is only one instance.

, , Append append. , , , . , , , .

+12

.

+2

There is actually a much faster way to do this:

string letsCount = "Let count! ";
string[] numbers = new string[100];
for(int i=0; i< 100; i++)
{ 
   numbers[i]=i+", ";
}
String.Join(letsCount, numbers);

Look here

+1
source

Source: https://habr.com/ru/post/1725018/


All Articles