Stack and heap are closely related with memory. Actually both are stored in computers RAM. Let's firstly look at what they are.
The Stack
Is a special region of the computer memory which holds temporary variables created by each function. This is managed and optimized by the CPU itself therefore you don't have to worry about allocating memory or anything as such.
When you enter a function the variables defined inside the function will be pushed into the stack and when you exit the function the variables will be cleared from the stack.
The stack is always reserved in LIFO (last in first out order). The stack is set aside for a thread. Each thread gets a stack.
Understanding stack in JavaScript (blog article)
In JavaScript sometimes you'll encounter Maximum call stack exceeded in JavaScript error. This happens when you exceed the call stack size in JavaScript. You can replicate this with a simple code like below
The Heap
Is the memory set aside for dynamic allocation. Unlike stack there is no pattern for allocation or deallocation of blocks from the heap. You must manually destroy variables on the heap.
Heap can have fragmentation when there are lot of allocations and deallocations happening. Heap is usually responsible for memory leaks as well.
In .NET unless you're building a compiler, knowing how stack and heap works is not needed much. (Stack vs. Heap in .NET - Stackoverflow).
0 comments:
Post a Comment