Why building a string in a loop gets slow

Strings never change. Every += makes a new one.

Why building a string in a loop gets slow

The problem

This builds 1000 strings to get one.

var line = "";foreach (var item in inventory){    line += item.Name + ", ";}

A string cannot be edited. Each += copies the whole thing into a new one and throws the old away.

What it costs

The work grows with the square.

Characters copied while joining names of 20 characters each:

100 items
0.11 million chars
500 items
2.76 million chars
1000 items
11 million chars

Ten times the items is a hundred times the copying.

The fix

Use a buffer that can grow.

StringBuilder keeps one block of memory and writes into it. You pay for the text once.

string +=
a whole new string, every pass
StringBuilder
one buffer that grows
string.Join
one call, no loop at all

Call ToString once at the end, when you actually need a string.

The fix in code

Append, then ToString once.

using System.Text; var sb = new StringBuilder();foreach (var item in inventory){    sb.Append(item.Name).Append(", ");}var line = sb.ToString();

Same result, one allocation that grows instead of one per item.

The rule

A loop building a string wants a buffer.

A few pieces
just use +
A whole list
string.Join
Built in a loop
StringBuilder

string.Join already does this. Try it before the loop.