A new is cheap, but each one is something for the garbage collector to clean up later. Most code should simply be clear. Only in hot paths, code that runs millions of times, does this become worth changing, and you should find those by measuring, not guessing.
Measure first
GC.GetAllocatedBytesForCurrentThread gives the bytes allocated so far, and it's a precise tool for comparing two approaches. Exact sizes vary, so this checks comparisons rather than numbers. Each += here creates a whole new string, copying everything so far.
using System.Text;
long Measure(Action action)
{
long before = GC.GetAllocatedBytesForCurrentThread();
action();
return GC.GetAllocatedBytesForCurrentThread() - before;
}
string resultA = "";
long concat = Measure(() =>
{
string text = "";
for (int i = 0; i < 1000; i++)
{
text += "x";
}
resultA = text;
});
string resultB = "";
long builder = Measure(() =>
{
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
sb.Append('x');
}
resultB = sb.ToString();
});
Console.WriteLine(resultA == resultB);
Console.WriteLine(concat > builder * 10);Check your prediction
True
TrueOn your own computer, measure with BenchmarkDotNet, which handles warm-up and statistics. Timings in this browser aren't meaningful for .NET in general, because the runtime is WebAssembly with one thread. Allocation counts are a much sturdier guide to carry over.
ArrayPool
If a method needs a big temporary array on every call, borrow one. ArrayPool<T>.Shared keeps returned arrays for reuse. There are two traps. You may get an array larger than you asked for, so use a slice of the right length, and it may hold old data, so never read what you haven't written. Return it in a finally, and never use it afterwards.
using System.Buffers;
byte[] borrowed = ArrayPool<byte>.Shared.Rent(100);
try
{
Console.WriteLine(borrowed.Length >= 100);
Span<byte> buffer = borrowed.AsSpan(0, 100);
buffer.Fill(7);
Console.WriteLine(buffer[99]);
}
finally
{
ArrayPool<byte>.Shared.Return(borrowed);
}
long before = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 100; i++)
{
byte[] array = ArrayPool<byte>.Shared.Rent(1024);
ArrayPool<byte>.Shared.Return(array);
}
long pooled = GC.GetAllocatedBytesForCurrentThread() - before;
before = GC.GetAllocatedBytesForCurrentThread();
for (int i = 0; i < 100; i++)
{
_ = new byte[1024];
}
long plain = GC.GetAllocatedBytesForCurrentThread() - before;
Console.WriteLine(pooled < plain);Check your prediction
True
7
TrueHidden allocations
Some code allocates without a new in sight. A lambda that captures a local variable needs a closure object to hold that variable, and a new delegate each time the lambda expression is evaluated. Some LINQ chains allocate an iterator for each step, and boxing allocates when a struct goes through an interface. These are all fine in normal code. They only matter in hot paths, and the only way to know which one you have is to measure.
int[] values = Enumerable.Range(0, 1000).ToArray();
int threshold = 500;
long Measure(Func<int> action)
{
long before = GC.GetAllocatedBytesForCurrentThread();
action();
return GC.GetAllocatedBytesForCurrentThread() - before;
}
int CountLoop()
{
int count = 0;
foreach (int value in values)
{
if (value > threshold)
{
count++;
}
}
return count;
}
int CountCaptured() => values.Count(value => value > threshold);
int CountStatic() => values.Count(static value => value > 500);
int CountChained() => values.Where(static value => value > 500).Count();
foreach (Func<int> warmUp in new Func<int>[] { CountLoop, CountCaptured, CountStatic, CountChained })
{
warmUp();
}
Console.WriteLine(CountLoop() == CountCaptured());
Console.WriteLine($"loop: {Measure(CountLoop)} bytes");
Console.WriteLine($"captured lambda: {Measure(CountCaptured)} bytes");
Console.WriteLine($"static lambda: {Measure(CountStatic)} bytes");
Console.WriteLine($"Where, then Count: {Measure(CountChained) > 0}");Check your prediction
True
loop: 0 bytes
captured lambda: 64 bytes
static lambda: 0 bytes
Where, then Count: TrueThe loop allocates nothing, as expected. The surprise is that LINQ itself isn't the cost here: Count with a static lambda allocates nothing either. A static lambda can't capture anything, so the runtime creates its delegate once and reuses it, and on .NET 10 Count over an array or a list walks the elements directly instead of creating an enumerator. The 64 bytes come from the captured threshold: that lambda needs a fresh delegate on every call. Chaining Where first does allocate, because Where returns an iterator object that Count then consumes; its size varies between runtimes, so the program only prints whether there was one.
Rules of thumb such as "LINQ always allocates" go out of date as the runtime improves. That's why the rule in this lesson is to measure.
Keep the fix in proportion
Faster code is usually harder code. Before you change something, ask three questions: Does a measurement show a problem? Does this code run often enough to matter? Does the change keep correctness easy to see? The job runner uses none of these tricks in its handlers, because its cost is dominated by waiting. A single network call dwarfs all of its allocations.
Also, string.Create, interpolated string handlers and SearchValues<T> are useful for specific hot paths, and they're worth exploring when you have a profile that points at them.
Your turn
Join without waste
Write JoinInts(ReadOnlySpan<int> values, char separator), returning something like 1,2,3. Use a StringBuilder with a sensible starting capacity. Compare its allocations against a Naive version using +=, with 500 values.
Print the result for 1, 2, 3; an empty result as [], in brackets; whether both versions match for the 500 values; and whether JoinInts allocated less than a third of what Naive did.
When it works, it prints:
1,2,3
[]
True
Trueusing System.Text;
var builder = new StringBuilder(16);
builder.Append(1).Append(',');
Console.WriteLine(builder);Hint 1: the idea
A separator goes between values, so add it before every value but the first. That one rule also takes care of the empty case and the single-value case.
Hint 2: a first step
Write JoinInts and check its output. Then write a Measure helper as above. Note that a lambda can't capture a span, so convert to an array at the call with a ToArray or keep an array in a variable.
Show one solution
using System.Text;
Console.WriteLine(JoinInts(new[] { 1, 2, 3 }, ','));
Console.WriteLine($"[{JoinInts(ReadOnlySpan<int>.Empty, ',')}]");
int[] values = Enumerable.Range(0, 500).ToArray();
long before = GC.GetAllocatedBytesForCurrentThread();
string naive = Naive(values, ',');
long naiveBytes = GC.GetAllocatedBytesForCurrentThread() - before;
before = GC.GetAllocatedBytesForCurrentThread();
string joined = JoinInts(values, ',');
long joinedBytes = GC.GetAllocatedBytesForCurrentThread() - before;
Console.WriteLine(naive == joined);
Console.WriteLine(joinedBytes * 3 < naiveBytes);
static string JoinInts(ReadOnlySpan<int> values, char separator)
{
var builder = new StringBuilder(values.Length * 4);
for (int i = 0; i < values.Length; i++)
{
if (i > 0)
{
builder.Append(separator);
}
builder.Append(values[i]);
}
return builder.ToString();
}
static string Naive(int[] values, char separator)
{
string result = "";
for (int i = 0; i < values.Length; i++)
{
result += i > 0 ? $"{separator}{values[i]}" : values[i].ToString();
}
return result;
}1,2,3
[]
True
TrueCompletion is saved in this browser only. It does not measure mastery.