Posts · 8 November 2026 · 6 min read · 48 reads

I Knew the Element Count, but I Made the List Guess Twenty Times

Filling a `List<long>` with two million elements through a plain `Add` loop reallocated the internal array twenty times and used twice the memory it needed. The measured cost, the one-line fix, and the LINQ patterns where the count is known upfront.

I needed to build a List<long> from an int array of two million elements, doubling each value. The loop I wrote without thinking was simple: a new list, one Add per element, done. But this started leaving small peaks on the gen0 graph. I couldn't understand why a plain Add loop would bother the garbage collector. There was a loop, and it only added elements.

I knew the code I wrote wasn't lying to me, so I decided to look.

The list kept rebuilding itself as it grew

List<T> doesn't know what its final size will be. So it starts small and doubles its capacity when it fills up. Each growth allocates a larger internal array, copies the old elements over, and leaves the old array for the garbage collector. Looked at alone, this seems reasonable. But I was going from zero to two million, so there were many growths, and each one left behind an array the collector had to clean up.

Instead of guessing how many times it happened, I counted. I wrote a small check that incremented a counter whenever the capacity changed. The result was twenty. Yet I already knew I wanted two million slots from the start. Twenty arrays had been allocated and thrown away to build a single list.

Putting numbers on it

I measured the way I always do: the smallest honest version, the best of seven runs, a GC.GetAllocatedBytesForCurrentThread() measurement around each run, and a checksum so a wrong result wouldn't pass silently. The source array is generated once up front, so it doesn't pollute the measurement.

static long FillWithCapacity(int[] source)
{
    var list = new List<long>(source.Length);
    for (int i = 0; i < source.Length; i++)
        list.Add((long)source[i] * 2);
    return list.Count;
}

The results came out like this:

  • Add loop without a capacity: about 33.5 MB allocated, about 11.2 ms
  • Add loop with the capacity given upfront: about 16 MB allocated, about 8.2 ms
  • Add loop with EnsureCapacity: again about 16 MB allocated

The finished list is 16 MB in both cases. Two million longs is already 16 MB of data. The remaining roughly 17.5 MB is pure waste. That's the total of the small arrays the list allocated, copied, and discarded while it grew. I was paying the cost of building the list twice and handing the second copy directly to the garbage collector.

The fix is a single argument. new List<long>(count) allocates the internal array once at the correct size and never grows it. If I already hold the list, EnsureCapacity(count) does the same job. Both bring you down to a single 16 MB allocation.

The framework sometimes does this already

What really changed how I write this was the following: I searched for other places where I was filling lists blindly, and found that some of them already worked correctly.

// The count is known, so the list is sized upfront
var list = source.Select(x => (long)x * 2).ToList();

// The count isn't known, so it grows gradually
var list2 = new List<long>();
list2.AddRange(source.Where(x => true).Select(x => (long)x * 2));

Select over an array followed by ToList() stayed at 16 MB. It can look at the array underneath the projection, get the element count, and size the result in one go. But the moment I added a Where to the chain, meaning I gave AddRange a lazy query, the allocation jumped back to 33 MB. Where can't tell in advance which elements will pass the condition. So there's no number the list can size itself to, and it grows by doubling again. The destination is the same, and so are the twenty reallocations.

So the rule "just use LINQ and don't worry" isn't quite right. The outcome depends on whether the count is still known when the list asks for it.

When I actually bother

I think of this as a narrow optimization, and I keep it narrow. I size the list upfront when I already have the count in hand: the Length of an array, the Count of an ICollection, or the number of rows I just read from a query. That information is free, and throwing it away isn't smart.

I don't do predictive sizing. If I don't really know the count and I pick a generous upper bound, you can waste more space than the reallocations would have cost. A list where you reserve a million slots but only put in a thousand elements holds 8 MB for nothing. Reallocations only become expensive when they pile up at scale. A list of twenty elements goes through four growths, and that's a rounding error nobody needs to think about.

The timing side was a quieter win along the way. Sizing upfront brought wall-clock time from about eleven milliseconds down to eight. That's real but modest. The environment isn't a lab; it's a cloud container with the workstation GC. So I trust the allocation rate far more than exact milliseconds. The allocation count is what makes this optimization actually felt; it usually shows up as garbage collector pressure just after the spot where the code looked innocent.

Key takeaways

  • If you already know the number of elements, start the list with that capacity. This stops the internal array from being copied over and over.
  • Reallocations pile up in large lists. In small lists their effect is negligible.
  • EnsureCapacity does the same job if you already hold the list.
  • ToList() can size the list in one go as long as it knows the count. A filter like Where removes that information.
  • Sizing with a guessed upper bound can cost more resources than reallocating, because it reserves unused capacity.
  • Millisecond differences vary by environment. The allocation amount is a more reliable measure.

When to use it

This approach makes sense when you already know the element count from somewhere else in the code, the list may be large, and you build it often. For example, when an array, a collection, or a row count you just read is available, size the list upfront. Don't force it when you don't know the count or you're filtering. In those cases, trusting the framework's own growth strategy usually gives a cleaner result than allocating memory you may not need.

Read the original article on DEV Community ↗

Comments (0)

No comments yet; be the first.

Leave a comment

Comments are published after approval.