Memory Allocation for Variable Declared in Class

前端 未结 4 747
灰色年华
灰色年华 2021-02-06 03:30

As Value type variable allocates memory in Stack where as Reference Type allocates it in Heap.

So how the memory allocated when a value type variable(eg int i =4;) is d

4条回答
  •  忘了有多久
    2021-02-06 04:10

    This is why Eric Lippert reminds us that the stack is an implementation detail.

    When an instance of a value type is a member of a reference type yes, it is stored on the managed heap along with the parent object. It's a good question and something you should understand, just not something that should drive your design in most scenarios.

    structs should be small, simple data types that are relatively cheap to create and pass around. Reference types are your complex types, require only a copy of the reference to pass to a method, but of course come with some baggage due to being allocated on the heap. Here is a good follow up post regarding the implications of stack versus heap allocations.

    There are plenty of references out there which explain the performance implications of value types versus reference types. You should learn all about it and also understand that, most of the time, it is a semantic decision, not a performance decision.

提交回复
热议问题