Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are value types garbage collected?

Tags:

.net

I understand there is garbage collection for reference types, but I'm wondering how garbage collection works for value types.

Do value types get garbage collected when they go out of scope?

like image 244
A.Sunil Kumar Avatar asked Jun 28 '11 05:06

A.Sunil Kumar


People also ask

Where are value types stored?

While value types are stored generally in the stack, reference types are stored in the managed heap. A value type derives from System. ValueType and contains the data inside its own memory allocation. In other words, variables or objects or value types have their own copy of the data.

Do global variables get garbage collected?

Global variables are always available from the root and will never get garbage collected. Some mistakes cause variables leak from the local scope into the global scope when in non-strict mode: assigning value to the undeclared variable, using 'this' that points to the global object.

How value types get collected V's reference types?

A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.

Is C# garbage collected?

Garbage collection (GC) is a memory recovery feature built into programming languages such as C# and Java. A GC-enabled programming language includes one or more garbage collectors (GC engines) that automatically free up memory space that has been allocated to objects no longer needed by the program.


1 Answers

Only storage allocated on the heap has to be garbage collected.

If a value type variable is on the heap, it's either part of some other class, or a boxed value, which is an object which only contains the value type value. The value is part of the memory which is "freed" when the containing object is garbage collected.

If a value type variable is on the stack, the memory it uses will be effectively "freed" when the stack frame is popped by the method returning.

Note that what ends up on the stack and what ends up on the heap is an implementation detail which is made more complicated by captured variables, iterator block, async methods, ref parameters etc. But the broad principle is that the memory used for value type values are always part of "something else" - so the it's reclaimed when the memory for that "something else" is reclaimed. (This isn't some sort of separate step - the value lives within the memory for that "something else" whether it's an object or a stack frame.)

like image 160
Jon Skeet Avatar answered Oct 18 '22 11:10

Jon Skeet