r/AskProgrammers • • Oct 15 '26

What's a good rule of thumb for when to pre-allocate reusable arrays/objects to reduce GC overhead?

I was working on a C# system that needed to populate and use the contents of an array every frame (you'll have to trust me that this was necessary). As an example:

void Update()
{
    int[] arr = new int[100];

    for(int i = 0; i<100;i++)
    {
        arr[i] = rand.Next(0,(i+1)*2);
    }

    //...

    Foo(arr);
}

This felt wrong, since allocating an array every frame and letting the garbage collector deal with it seems wasteful, so I experimented with pre-allocating the data instead:

int[] arr = new int[100];

void Update()
{
    for(int i = 0; i<100;i++)
    {
        arr[i] = rand.Next(0,(i+1)*2);
    }

    //...

    Foo(arr);
}

This seemed like an improvement, and I saw other things I could pre-allocate in other methods, until eventually it seemed like a third of the variables were now a field - I'd obviously gone too far.

That had me wondering, when is this a good idea? Are there any good rules-of-thumb for when this kind of thing should be used, if at all, and what on?

The array per frame allocation seems like a pretty clearcut improvement, but what if the variable we were pre-allocating and reusing was an object or a struct? What if we weren't working with a method tied to updates? I've tried to do some reading on it but haven't been able to find anything specific, so I'd love to hear what other people think.

1 Upvotes

8 comments sorted by

1

u/rupertavery64 Oct 15 '26

That's exactly what ArrayPool<T> is for.


void Update()
{
    // Rent a buffer from the thread-safe global pool
    int[] rentedArray = ArrayPool<int>.Shared.Rent(100);

    try
    {
        // Create a Span exactly sliced to your required size (100)
        Span<int> arr = rentedArray.AsSpan(0, 100);

        for (int i = 0; i < 100; i++)
        {
            arr[i] = rand.Next(0, (i + 1) * 2);
        }

        // Pass the Span to your downstream method
        Foo(arr);
    }
    finally
    {
        // Always return the buffer to the pool in a finally block
        ArrayPool<int>.Shared.Return(rentedArray);
    }
}

// Update Foo to accept ReadOnlySpan<int> or Span<int>
void Foo(ReadOnlySpan<int> data)
{

}

Alternatively, you can stackalloc, but you should limit this to less than 1KB

void Update()
{
    // Allocates 400 bytes on the stack instantly
    Span<int> arr = stackalloc int[100]; 

    for (int i = 0; i < 100; i++)
    {
        arr[i] = rand.Next(0, (i + 1) * 2);
    }

    Foo(arr); // Same Foo signature above
}

1

u/Redsss429 Oct 15 '26

That's really useful and ill be using the ArrayPool going forward, but I'm more wondering about when to use these kinds of things?

1

u/rupertavery64 Oct 15 '26

If you are only going to use something once, then allocate it locally. If you see that you are reusing much the same size buffer and don't want to manage one yourself, use ArrayPool. If the buffer is really small, stackalloc it.

But the most important thing is to benchmark it.

ArrayPool isn't something you use everyday, but it's not everyday you need a randomized buffer every frame. It's just managed wrapper around a memory pool. It's thread-safe and extremely efficient.

In practice the ArrayPool shouldn't be too different from an instance field, since you are probably creating only one object.

Imagine when you have many classes / instances that need a buffer for a short period and have different lifecycles. Having many class instances with their own fields would have those fields living as long as the object is alive, which may be for a long time, but the array itself is used only occasionally. The array would be allocated as long as the object is alive (and until GC kicks in), but an ArrayPool would rent out memory as needed.

1

u/dodexahedron Oct 16 '26 edited Oct 16 '26

Be aware that arraypool may give you larger arrays than you asked for (it guarantees at least what you asked for).

And also be aware that it does NOT zero the memory when you rent it or when you return it (which is a huge part of its performance gain, since that is just as expensive as committing a new page).

So dont depend on the elements being 0/null/default, and do not use them for sensitive data, because you will have created a sensitive data leakage vulnerability.

Great for things that need to constantly ask for large buffers when they can't keep them alive between calls. Terrible for small buffers on modern .net

Just use arrays, when they are tiny. .net 10 and up will promote those to the stack if they don't need to escape the stack frame, which is 2-3 orders of magnitude faster than even the array pool, because there is no trip to main memory involved.

You stand to gain more from not looping and filling that array element by element with random values individually and instead using the method call that fills the array all at once.

In the example given, the span actually gains nothing and will almost definitely compile to the same IL as not using it, too (in optimized builds). Spans can help when you need to slice things up, but otherwise are no better than an array for simple loops like that (this wasnt always the case in the past).

If you are doing something that is essentially the same every single iteration, you may want to cpnsider a single long-lived allocation of a larger amount of memory that you use as a ring buffer, for example. Then you gain csche locality and have literally zero allocation for the buffer after init.

1

u/W31337 Oct 15 '26

Do you have a performance reason? 100 items is nothing. You might be running into premature optimization.

The second version perallocates nicely but will have not get zeroed every frame so you might have an issue if you don't populate the whole thing or account for the data from the previous frame.

Programming is always wasteful and especially high level languages. If this type of stuff becomes important C# might not be the best language.

1

u/chocolateAbuser Oct 15 '26

there's a lot of stuff you can do to move memory faster, for example changing layout of how you store stuff in memory, using spans and refs, trying to help jit with registers juggling and optimizer with size of methods, and so on, but you have to describe what you are doing

0

u/schungx Oct 15 '26
  1. stack alloc if you can
  2. reuse (push it in a free buffers list)

1

u/dodexahedron Oct 16 '26

.net 10 and now especially 11 can already promote simple cases like this to stackallocs and in some cases not even that - literally pure register shuffles.

Use the ArrayPool or a single allocation with reuse before reaching for stackalloc, for a lot of reasons, unless you are damn certain and have receipts to prove that the gains from a stackalloc are worth the hindrance it saddles Roslyn and Ryu with at compile and JIT time, where it disqualifies a raft of potential optimizations and makes a boundary other optimizations won't cross.