views:

141

answers:

3

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 + ", ");
}
+12  A: 

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.

Josh Einstein
I think you should try out, using a stopwatch, it is very well measurable, that using a stringbuilder is faster already at more than 4-5 concatenations.
BeowulfOF
I am well aware of the benefits of using a stringbuilder for multiple concatenations. I was referring to the difference between Append(i+sep) and Append(i); Append(sep); x 100.
Josh Einstein
I did take your advice though and time it. x100 - 0ms (72 ticks) vs 0ms (61 ticks), x100000 - 32ms (71,517 ticks) vs 26ms (58,870 ticks)
Josh Einstein
+1 This interesting analysis leaves me wondering about the "internal cost" of the (apparently) automatic conversion of the loop index variable from int to "whatever" (so it can be concatenated with the SB). Also raises the interesting question, for me, of under what circumstances (if any) "chained" appends like : "s1.Append(i).Append(s2);" would have a "payoff." thanks,
BillW
+2  A: 

They are identical.

Jason
+1  A: 

Actually a much faster way to do it would be

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

See here

JanHudecek
Very interesting, thanks for the link. I'll have to remember that in the future. I'd be curious to see that graph after there were 100 concatenated strings...
Abe Miessler