In C#, what does the compiler emit for `id + "," + sku + "," + qty`, and when is `+` cheaper than StringBuilder?
answer
- one call per expression
- four operands, then an array
- constants fold at compile time
- loops are the exception
basics
~20 sOne string.Concat call per expression: up to four operands use fixed-arity overloads, five or more go in a string array, and adjacent constants fold at compile time. Fixed parts allocate once; StringBuilder wins only when parts arrive in a loop.
solid answer
~50 sThe compiler flattens a chain of `+` on strings into a single `string.Concat` call. Two to four operands go to `Concat(string, string)` up to `Concat(string, string, string, string)`; five or more are packed into a new `string[]` for `Concat(string[])`, so the five-operand example is one call over a five-element array. Adjacent constant strings are folded at compile time: with `const string Sep = ","`, the expression `"order" + Sep + "42"` compiles to the literal `"order,42"` and no call at all. A non-string operand such as an `int` gets `ToString()` called on it first. `Concat` allocates the result once, so a fixed expression is already as cheap as it gets; a `StringBuilder` would add a builder, its buffer and a final copy. The balance flips when the part count depends on data: `s += part` in a loop is a new `Concat` on every pass.
code
csharp · 15 linesconst string Sep = ",";
string id = "1007", sku = "SKU-42", qty = "3";
int count = 3;
string folded = "order" + Sep + "42"; // the literal "order,42": no call at run time
string four = id + Sep + sku + Sep; // string.Concat(string, string, string, string)
string six = id + Sep + sku + Sep + qty + "\n"; // string.Concat(string[]) over a new 6-element array
string mixed = "qty=" + count; // count.ToString(), then string.Concat(string, string)
string looped = "";
foreach (string part in new[] { id, sku, qty })
looped += part; // string.Concat(string, string) on every pass
Console.WriteLine(ReferenceEquals(folded, "order,42")); // True
Console.WriteLine(four + "|" + six.TrimEnd() + "|" + mixed + "|" + looped);go deeper
Remember that a + b + c in one statement is fine, while += inside a loop is the pattern to replace with StringBuilder or string.Join.
Explain the lowering: one string.Concat per expression, the two-to-four overloads, a string array from five operands, folding of adjacent constants, and ToString on non-string operands.
Use the lowering to judge code: flag + inside loops and Append(a + b), keep fixed expressions as +, and note that ToString on numeric operands uses the current culture.
Turn it into team guidance that resists cargo-cult rules: no blanket ban on +, StringBuilder or string.Join when the part count depends on data, and readability first for fixed expressions.
## One call per expression When the C# compiler sees `+` between strings, it does not emit one operation per plus sign. It **flattens** the whole chain into a list of operands and emits a single call to `System.String.Concat`. `Concat` first adds up the lengths of all operands, allocates one string of exactly that length and copies each operand into it. A chain of five strings therefore allocates one result string, not four intermediate ones. ## Which overload the compiler picks The SDK 10.0.401 compiler chooses by operand count and type, as its lowering code and the compiled IL show: | Expression shape | What the compiled code calls | |---|---| | Only constants, such as `"order" + Sep + "42"` with `const string Sep` | nothing: the folded literal `"order,42"` | | 2 to 4 strings | `Concat(string, string)` up to `Concat(string, string, string, string)` | | 5 or more strings | `Concat(string[])`, with a new array holding the operands | | A non-string operand, such as `"qty=" + count` | `count.ToString()`, then the string overload | | 2 to 4 operands mixing strings and non-constant `char` values | the `Concat(ReadOnlySpan<char>, ...)` overloads | So `id + "," + sku + "," + qty` with three string variables has five operands and compiles to one `Concat(string[])` call over a five-element array. The array is a small extra allocation, but there is still exactly one result string. ## Constant folding Adjacent constant strings and `const string` fields are combined by the compiler before any code runs: - `"order" + Sep + "42"` with `const string Sep = ","` becomes the literal `"order,42"`; at run time nothing is concatenated. - Because it is a literal, it is the same interned instance as any other `"order,42"` literal in the program, which is why `ReferenceEquals(folded, "order,42")` prints `True`. - Only **consecutive** constants fold: in `id + "," + sku + ","`, the commas are separated by variables and stay as separate operands. - A `static readonly string` is not a constant, so it never folds. ## Non-string operands For an operand that is not a string, the compiler calls its `ToString()` and passes the result to a string overload, which avoids boxing a value type into `object`. Two consequences follow. First, a `decimal`, `double` or `DateTime` operand is formatted with the **current culture**, exactly as its parameterless `ToString()` would; how to control that belongs to the lesson on formatting. Second, a `null` operand is harmless: `string.Concat` treats null as an empty string, and the two-argument overload returns the other operand unchanged when one side is null or empty. ## Where `+` stops being cheap The single-call guarantee covers **one expression**. In a loop: ```csharp string s = ""; foreach (string part in parts) s += part; // string.Concat(string, string) on every pass ``` Each pass is a separate expression, so each one allocates a new string holding all the text so far. Total copying grows with the square of the part count. The replacements: 1. **The parts are already in a collection:** `string.Join(separator, parts)` or `string.Concat(parts)`. For a `List<string>` or an array, `Join` sums the lengths, allocates once and copies once. 2. **The parts are produced one at a time:** `StringBuilder.Append` in the loop, then `ToString()` once. 3. **A fixed number of parts in one statement:** keep `+`; it is already one allocation. ## Why reviewers still flag `+` - `+` inside a loop, or inside a method that a loop calls for every row, is the real quadratic trap. - `sb.Append(a + "," + b)` builds a temporary string before appending; chaining `Append(a).Append(',').Append(b)` writes straight into the builder. - Rewriting a one-line `a + b + c` as a `StringBuilder` makes code longer and slightly slower, because it adds a builder object, a buffer and a final copy on top of the result string. The short version for an interview: one expression is one `Concat` and one allocation, constants cost nothing at run time, and only data-dependent repetition needs `StringBuilder` or `string.Join`.
- Does `string.Join(",", fields)` over a `List<string>` allocate more than a StringBuilder would?Usually less. For a `List<string>` or an array, `string.Join` reads the elements as a span, adds up their lengths and the separators, allocates the result once and copies each element once, with no builder object. For other `IEnumerable<string>` sources it falls back to an internal growable buffer that starts on the stack, so it still skips the `StringBuilder` allocation.
- What happens when one operand in the chain is null?Nothing fails: `string.Concat` treats a null operand as an empty string, so `null + "x" + o` with a null object `o` gives `"x"`. The two-argument overload goes further and returns the other operand itself, without allocating, when one side is null or empty.
- Why can `"total: " + price` with a `decimal price` print differently on two servers?The compiler calls `price.ToString()`, and the parameterless `ToString()` formats with the current culture, so the decimal separator follows each server's settings. The concatenation itself is identical; controlling the format, for example with an invariant culture, is a formatting decision rather than a concatenation one.
- Every + in a chain allocates its own intermediate string.
- A one-line a + b + c should be rewritten with StringBuilder for speed.
- Concatenating constant strings costs a Concat call at run time.
- The compiler boxes an int operand into object before concatenating it.
- s += part inside a loop is optimised into one Concat call.