c# - What is major importance/role of stack memory if most of the data go on heap? -
i reading dispose pattern , come across how memory allocated. following quote http://codebetter.com/karlseguin/2008/04/28/foundations-of-programming-pt-7-back-to-basics-memory/.
memory allocation
....
....
exception rule value types belonging reference types – example id property of user class goes on heap along instance of user class itself.
this mentioned on question on stack overflow here. memory allocation value type inside reference type in .net
my understanding that, value types irrespective of declared go stack. looks wrong now. in code below, i
go on heap; not on stack according links. because myclass
reference type go heap , along it, value types.
class myclass() { int = 5; }
ok, value types not part of class go stack memory then. right? but, in dot net language c# inside class. go stack memory?
this answer explains value types go heap.
if case, there little or near nothing goes on stack memory.
i suspect misunderstanding something.
if data goes heap memory, not understand importance/role of stack memory.
please explain.
following 2 articles explains memory management in simple way.
don't think of "stack" , "heap". think of short term memory , long term memory. becomes easy know goes on stack , goes on heap. is lifetime of variable longer activation of current method? if yes, not short-lived, , has go on heap. if is, can go on stack.
for example:
class c { void m() { string s = whatever(); something(s); } }
the local variable s
can go on short term pool because not last longer activation of method.
now, might wait minute, string reference type, surely goes on heap. , no, not. the string goes on heap, variable not contain string. string reference type the variable contains reference, , a reference can go on stack. thing refers to on heap, reference itself value, , can go on stack.
so stop thinking type of determines stored. type irrelevant. variables of value type or reference type can go on short term pool if short-lived, , must go on long term pool if not.
now about
class c { void m() { int = whatever(); x(() => i) } }
now can go on stack? no. x
store copy of delegate passed in, , delegate needs know value of i
, variable needs live longer activation of method m
, i
goes on long-term pool. i
on heap here.
again, fact int irrelevant. it's variable, lives long time, goes on heap.
what fields of class, or elements of array? variables. live long class instance or array instance lives, , therefore lifetimes not predictable, , therefore go on long-term pool.
why have short term pool , long term pool? because garbage collector short term pool extremely fast , cheap compared garbage collector long term pool. want have option of generating variables on short term pool when can -- when lifetimes short.
Comments
Post a Comment