5YrsLaterDBA
5YrsLaterDBA

Reputation: 34780

How GC cleanup the struct?

I think the GC may treat reference type and value type differently.

GC will collect the reference type if there is nobody have a reference to it. When GC will collect the value type like struct? My struct is not small. I want it be collected as earlier as possible. With a profiler software, I saw that struct has a big accumulation and is the major memory consummer.

Upvotes: 1

Views: 744

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1501626

A struct will only be in the managed heap (i.e. where it can be garbage collected) if it's either an instance/static field, or as part of another object, or boxed, or in an array1. It's never "naked" in the managed heap - the closest you can get is a boxed value.

If you have a large struct, that's your first problem. Why have you created such a thing? Structs should almost always be small (the rule of thumb is usually 32 bytes) as otherwise every time you use it as a method argument or assign it to another variable, you'll end up copying it.

Have you considered using a class instead?


1 As Eric Lippert is fond of pointing out, the stack is an implementation detail. Furthermore, in certain cases local variables end up as fields in autogenerated classes... but that's somewhat irrelevant for this question, I believe.

Upvotes: 6

zgr
zgr

Reputation: 11

A struct type is a value-type and inherits from System.ValueType. Value-type variable is allocated on the current thread's stack (not on the heap). Memory is not allocated on the managed heap. It is allocated on the stack and is automatically freed when value-type variable go out of scope. But if you are making the boxing of value-type variable then memory is allocated on the heap for variable's wrapper and variable's fields are copied to the wrapper. If your value-type variable is larger than 85KB it's wrapper will be placed in Large Object Heap (LOH). LOH objects are long living - they belong to Gen2.

Upvotes: 1

Related Questions