Did you know… string concatenation

August 12th, 2007

... that simple strings concatenating in C# can have impact on memory usage?
Let's look at this simple code:

C#:
string foo = "foo";
foo += " bar";
foo += " bar2";
foo += " bar3";

This causes that the compiler creates 3 additional strings on the stack, then garbage collector must clean it. Only the last string has a reference. If you make something like this very often in a loop consider using string's Concat or Join methods. StringBuilder is also a good choice.

Leave a Reply

Designed by SirMike © All rights reserved

Valid XHTML 1.0! Valid CSS!