Monday, May 29, 2017

Value Type and Garbage Collector Role

Garbage Collector play no role in de allocation of value type variable.

The stack is a block of pre-allocated memory one million bytes in size. Sometimes we use portions of that block of memory to store local variables of value type.The stack never changes in size; it's a one-million-byte block of pre-allocated memory.

The stack is divided into two contiguous regions, which we'll call the "valid" and "invalid" sections of the stack. On x86 architectures the ESP register points to the boundary between those regions.

The stack is an implementation detail of a specific version of the runtime.

In a multi-threaded situation each thread will have its own completely independent stack but they will share the heap. Stack is thread specific and Heap is application specific. The stack is important to consider in exception handling and thread executions.

Difference between stack and Heap

The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO (last in first out) order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.

The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.

Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation).
  • Both are stored in computer RAM.
  • Stack is faster than heap.
  • Variables created on the stack will go out of scope and automatically deallocated.
  • Data items on stack are allocated and deallocated by CPU; therefore memory will be managed efficiently, there will be no memory leaks and memory will not become fragmented.
  • Variables once allocated on to the stack cannot be resized.
  • Variables allocated from heap region can be resized using realloc()
  • Memory allocated from stack is called static memory allocation.
  • While, memory allocated from heap is called dynamic memory allocation.
Can you implement IDisposable for value type ?
Structs being a value type can inherit IDisposable interface

No comments:

Followers

Link