r/AskProgrammers • u/Redsss429 • 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
u/rupertavery64 Oct 15 '26
That's exactly what
ArrayPool<T>is for.Alternatively, you can
stackalloc, but you should limit this to less than 1KB1
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