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?
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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With