Is it better, from a performance standpoint, to use “Example1”? I’m assuming that “Example2” would create a new string on the heap in each iteration while “Example1” would not…
Example1:
StringBuilder letsCount = new StringBuilder("Let's count! ");
string sep = ", ";
for(int i=; i< 100; i++)
{
letsCount.Append(i + sep);
}
Example2:
StringBuilder letsCount = new StringBuilder("Let's count! ");
for(int i=; i< 100; i++)
{
letsCount.Append(i + ", ");
}
The .NET CLR is much smarter than that. It “interns” string literals so that there is only one instance.
It’s also worth noting that if you were truly concerned about string concatenation, you would want to turn the single Append call into two append calls. The reality, however, is that the overhead of two calls probably outweighs any minor concatenation cost. In either case, it’s probably nearly immeasurable except in very controlled conditions.