string myString = string.Empty;
for (int i = 0; i < 100; i++)
myString += i; // Non compliant : this requires a new string allocation on each iteration
Don’t concatenate strings in loops, use a StringBuilder instead.
strings are immutable so each time they are concatenated, a new one is created. When in a loop, this can lead to a waste of memory and CPU time.
In comparison, a StringBuilder works with a single mutable buffer, from which a resulting string can be allocated when needed.
If the number of concatenations is very small, typically 5 or less, then the overhead cost is either marginal or non-existent, and can be ignored.
string myString = string.Empty;
for (int i = 0; i < 100; i++)
myString += i; // Non compliant : this requires a new string allocation on each iteration
var builder = new StringBuilder(); // Creating the buffer itself requires an allocation
for (int i = 0; i < 100; i++)
_ = builder.Append(i); // Update the buffer, no allocation required
string myString = builder.ToString(); // Triggers a string allocation, but only once