Noggog
Noggog

Reputation: 83

Garbage Collection During Simple Allocations

So I was tracking down what I thought was excessive GC during some of my code. I eventually boiled it down to this code that showed what I was seeing:

object[] ret = new object[40000000];
for (int i = 0; i < 40000000; i++)
{
    ret[i] = new object();
}

While running that loop, I was seeing dozens of Garbage Collection Gen1 events. Does anyone have a good understanding of why this is? What no-longer-referenced objects is it cleaning up while filling this array?

Here's a picture as more reference: https://i.sstatic.net/mPQ91.jpg

I wouldn't expect any GC to be happening until I lost reference to an object I created. Maybe I'm being braindead today or there's some fundamental concept I'm missing, but it seemed curious to me.

Thanks!

Upvotes: 1

Views: 62

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062650

Just because it ran a gen1 doesn't mean it collected anything - it means it tried (precisely because you had allocated lots of objects!). It doesn't know, until it tries, whether it will succeed.

I wouldn't expect any GC to be happening until I lost reference to an object I created.

Nope; GC collects object that aren't reachable, but it runs whenever it feels is appropriate (for example, based on allocations - or due to external memory pressure from the OS).

Upvotes: 2

Related Questions