Interview frequency: …
Short answer
Every edit or concatenation (+) creates a new string object on the Heap; use StringBuilder in loops and String.Create to produce strings of known length without allocations.
Explanation
Concatenating strings in a loop for 1,000 items with text += item allocates 1,000 temporary string objects on the Heap. StringBuilder collects segments in one growable internal buffer. For maximum performance (.NET Core+), string.Create(length, state, action) allocates the final string once and writes directly into its internal Span without temporary objects.
Code example
// Extremely high performance and maximum speed for building strings without temporary arrays
string id = string.Create(8, state, (span, s) => {
// Fill the span directly
});Common mistakes
- Using StringBuilder to join two or three simple strings on one line; the compiler already optimizes simple concatenations with + more efficiently than StringBuilder.