-
Stack , HeapC# 2019. 6. 1. 17:36
What is "Stack"-A Memory space to run a program, memory which is needed when calling method is saved here.
Stack Frame
-A memory for calling method is mandatory in stack.
A bundle of memory that are needed for a method is called "Stack Frame".
-In other words, each method demands each Stack Frame which is consisted of local value, parameter, return value.
Method Call and Stack Memory
-When you call a method, a stack frame is created in stack.
The stack memory is deleted from stack memory as soon as call is done.
Basic structure of stack is Last in First Out(LIFO).
Let's suppose there are Calc() Method in Main(), Sum() in Calc().
When program is started, Main() is saved in this stack, followed by Calc() and Sum().
Then which of those 3 method will be ended first? No doubt that the answer is Sum().
As stack memories delete all the memories relevant to method, Sum() is deleted first in the stack.Calc() and Main() are next.
What is Heap?
-Memory in C# is consisted of Stack and Heap. Heap is opposite concept to Stack.
When Local value, Parameter and Return value are saved in Stack
Memory that is created with "new" keyword is saved in Heap.
In summary, value that are declared in method is saved in Stack, else are saved in Heap.
upper Image shows which value is saved in Stack while others are saved in Heap.
Red circles refers values that are saved in stack, blue circles are in Heap.
Heap Memory Removal
Memory in stack is deleted as call is ended. Namely, Memory is removed where braces are closed.
Then how about Heap?
There's Garbage Collector in C# which clears Heap Memory by itself.
Garbage Collector keep eyes on Heap memory, removes Unnecessary or Unused memory and conducts
Memory defragmentation when memory's deficient.
Every memory that is created with "new" keyword is under controlled by Garbage Collector so that users don't need to take care of it.
however if you want to clear Heap memory, you can enforce to call Garbage Collector by using GC.Collect().
출처:http://blog.naver.com/PostView.nhn?blogId=cjej1004&logNo=110100887961
'C#' 카테고리의 다른 글
C# polymorphism (2/4) - Override (0) 2019.06.06 Indexer (0) 2019.06.06 C# polymorphism (1/4) - Overloading (0) 2019.06.05 Params (0) 2019.06.04 Boxing, UnBoxing (0) 2019.05.30