c# structs/classes stack/heap control?

前端 未结 5 865
醉梦人生
醉梦人生 2021-02-01 09:02

so in c++ it\'s very easy. you want whatever class/struct to be allocated on the heap, use new. if you want it on the stack, don\'t use new.

in C# we always use the new

5条回答
  •  不思量自难忘°
    2021-02-01 09:32

    Your explanation of where value types vs. reference types go (stack v. heap) is not completely correct.

    Structs can also get allocated on the heap if they are members of a reference type for example. Or if you have boxed them while passing them via an object reference.

    You should read http://www.yoda.arachsys.com/csharp/memory.html to get a better understanding of where different types actually are allocated.

    On a separate note, in .Net, you really shouldn't care about where a types is allocated - as Eric Lippert writes: the stack is an implementation detail. You are better off understanding the semantics of how types are passed (by value, be reference, etc).

    Furthermore, you seem to be making an implication that allocating an object on the heap is more expensive than on the stack. In reality, I would argue that the performance cost of copying value types outweighs the benefit of any savings in a slightly quicker allocation on the stack. The biggest difference between stack and heap, is that on most CPU architectures the stack is more likely to be retained in CPU cache - and thereby avoid cache misses.

    This is not the most important issue to be concerned with. You should decide whether the type should have pass-by-value semantics or not. If it doesn't - then perhaps it should be a reference type.

提交回复
热议问题