1.3 — String Immutability, StringBuilder, Interning¶
← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.2 struct vs class vs record · Next: 1.4 Access modifiers
Markers: ⭐ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
- A
stringcan never be changed once created. Every method that looks like it changes a string actually creates a brand new one. - Joining strings inside a loop is slow in a way that gets worse and worse. Use
StringBuilderwhen you do not know how many times you will join. - Interning means C# stores just one copy of each identical text written directly in your code, to save memory.
The concept¶
string is a class, so it is a reference type. But it behaves like a value type in the
two ways you notice day to day:
==compares the text, not whether they are the same object.- You cannot change it after it is made.
That second point — immutability — is the root of everything else in this note. Once you really believe "strings never change", the rest follows naturally.
How it works¶
Every string operation makes a new string¶
string s = "hello";
s.ToUpper();
// This does NOT change s.
// It creates a NEW string "HELLO" and returns it.
// We threw that new string away, so nothing happened.
s = s + " world";
// This creates a NEW string "hello world"
// and points s at it. The old "hello" is now garbage.
s.Replace('l', 'L');
// Again — creates a new string, returns it, we ignore it.
Here is the classic beginner bug, and it is worth recognising instantly:
string name = " Ada ";
name.Trim();
// Does nothing useful! Trim() returns a trimmed copy,
// but we never stored it. 'name' still has the spaces.
name = name.Trim();
// Correct. We store the new string back into name.
Why joining strings in a loop is slow¶
Because strings cannot change, each += has to:
- work out how long the new string will be
- allocate a brand new string of that size
- copy everything accumulated so far into it
- copy the new bit on the end
- throw the old string away
So on loop number 5,000 it is copying 5,000 characters. On loop 9,000 it is copying 9,000. The total work grows like the square of the number of loops. Programmers call this O(n²) — meaning if you double the input, the work goes up four times.
You also create 10,000 dead strings for the garbage collector to clean up.
StringBuilder fixes this. It keeps one internal buffer (a resizable array of characters)
and writes into it directly:
var sb = new StringBuilder();
for (int i = 0; i < 10_000; i++)
sb.Append(i); // writes into the existing buffer
string result = sb.ToString(); // ONE string created, right at the end
But do not use StringBuilder for everything. If you are joining a fixed, small
number of pieces, plain + is actually faster:
The compiler is smart here. It turns that whole line into a single String.Concat call,
which allocates exactly one string. A StringBuilder would be more code and slightly
slower.
The rule: loops and unknown counts → StringBuilder. A fixed handful of pieces →
plain + or string interpolation.
Two other options worth knowing:
string.Join(", ", items); // best when joining a collection
$"Hello {name}, you are {age}"; // interpolation — clear and efficient
Interning — sharing identical text¶
.NET keeps a pool (a shared list) of every piece of text written directly in your source code. If the same text appears twice, both places point at the same single string object in memory. This is called interning, and it saves memory.
string a = "hello";
string b = "hello";
ReferenceEquals(a, b);
// TRUE — both point to the same object.
// The compiler saw the same text twice and reused it.
string c = new string("hello".ToCharArray());
ReferenceEquals(a, c);
// FALSE — this string was built while the program was running,
// so it did not come from the pool.
ReferenceEquals(a, string.Intern(c));
// TRUE — string.Intern() looks the text up in the pool
// and gives you back the shared copy.
string d = "hel" + "lo";
ReferenceEquals(a, d);
// TRUE — both pieces are known at compile time,
// so the compiler joins them before the program even runs.
Be careful with string.Intern. Anything you put in the pool stays there for the
entire life of the program and can never be garbage collected. Interning user input is
effectively a memory leak that grows forever.
Comparing strings properly¶
a == b // compares the text
a.Equals(b, StringComparison.OrdinalIgnoreCase) // ignore upper/lower case
string.Equals(a, b, StringComparison.Ordinal) // exact, character by character
ReferenceEquals(a, b) // same object? rarely useful
Always say how you want to compare. Some string methods use the current culture — the language and region settings of the machine running the code. That means the same code can give different answers on different computers.
The famous example is Turkish. In Turkish, the capital of "i" is "İ", not "I". So
"file".ToUpper() gives "FİLE" on a Turkish machine, and a comparison against "FILE"
fails. Real systems have broken this way.
Simple guide:
- Comparing IDs, keys, file paths, or anything the computer uses → StringComparison.Ordinal
- Sorting or comparing text a human will read → culture-aware comparison
Code¶
// BAD: slow, and creates thousands of dead strings
var csv = "";
foreach (var row in rows)
csv += row + ",";
// GOOD: one buffer, one string at the end
var sb = new StringBuilder();
foreach (var row in rows)
sb.Append(row).Append(',');
var csv = sb.ToString();
// BEST for this specific job — clearer and handles the separator for you
var csv = string.Join(",", rows);
// FINE — fixed number of pieces, compiler makes this one Concat call
var greeting = "Hello, " + firstName + " " + lastName + "!";
// SAFE comparison — same result on every machine, in every country
if (string.Equals(input, "admin", StringComparison.OrdinalIgnoreCase))
{
// ...
}
Interview questions¶
Q: Why are strings immutable in .NET?
There are three reasons and they support each other. First, thread safety — if a string can never change, many threads can read it at the same time with no locking at all. Second, it makes interning and hash-code caching possible — a string can safely be a dictionary key, because its hash can never go stale. Third, security — if you validate a file path and pass it to a method, that method cannot change it behind your back after the check has passed.
Q: What is the difference between string and StringBuilder?
A string cannot be changed, so every modification creates a whole new string and copies
the old contents across. In a loop, that means the work grows with the square of the
number of iterations. StringBuilder keeps one internal buffer and writes into it,
growing it when needed, so the work grows in a straight line. But for a small fixed number
of joins, plain + is actually better, because the compiler collapses the whole
expression into a single String.Concat call that allocates once.
Q: What is string interning?
.NET keeps a pool of the text literals written in your source code, so if the same text
appears in several places they all share one object in memory. That saves memory for
repeated text. Literals go in automatically. Strings built while the program runs do not,
though you can add them with string.Intern. You usually should not, because the pool is
never cleaned up — anything you intern lives for the whole life of the process.
Q: Does == on strings compare the text or the object?
The text. string specifically overrides == to compare contents, which is an exception
to how reference types normally behave. That exception exists because comparing two
strings by memory address is almost never what anyone actually wants. If you genuinely
need to know whether they are the same object, you use ReferenceEquals.
Traps ⚠️¶
name.Trim();on its own line does nothing. String methods return a new string. They never change the one you called them on. Always assign the result.StringBuilderfor two or three joins is slower, not faster. The compiler already optimises fixed concatenation.- Default comparison can depend on the machine's language settings.
ToLower(),ToUpper()and someCompareoverloads use the current culture. PassStringComparison.Ordinalfor anything the computer uses internally. string.Internon user input leaks memory. The pool is never cleaned.null,""and" "are three different things. Usestring.IsNullOrEmptyorstring.IsNullOrWhiteSpacerather than comparing against"".Lengthcounts storage units, not visible characters. Strings are stored as UTF-16, so an emoji or a character from many scripts counts as 2 or more.
Related¶
- 1.1 Value vs reference types — why
stringis the odd one out - 1.25
Span<T>— cutting up strings without allocating - 3.4 Garbage collection — what all those dead strings cost
- 19.13 Reducing allocations — string handling in fast code