Why are structs stored on the stack while classes get stored on the heap(.NET)?

前端 未结 11 657
你的背包
你的背包 2020-12-01 03:05

I know that one of the differences between classes and structs is that struct instances get stored on stack and class instances(objects) are stored on the heap.

Sinc

相关标签:
11条回答
  • 2020-12-01 03:24

    That's a great question; I did not cover it in the article that Marc Gravell linked to. Here's part two:

    https://docs.microsoft.com/en-us/archive/blogs/ericlippert/the-stack-is-an-implementation-detail-part-two

    0 讨论(0)
  • 2020-12-01 03:25

    In some languages, like C++, objects are also value types.

    To find an example for the opposite is harder, but under classic Pascal union structs could only be instantiated on the heap. (normal structs could be static)

    In short: this situation is a choice, not a hard law. Since C# (and Java before it) lack procedural underpinnings, one can ask themselves why it needs structures at all.

    The reason it is there, is probably a combination of needing it for external interfaces and to have a performant and tight complex (container-) type. One that is faster than class. And then it is better to make it a value type.

    0 讨论(0)
  • 2020-12-01 03:25

    Marc Gravell already explained wonderfully the difference regarding how value and reference types are copied which is the main differentiation between them.

    As to why value types are usually created on the stack, that's because the way they are copied allows it. The stack has some definite advantages over the heap in terms of performance, particularly because the compiler can calculate the exact position of a variable created in a certain block of code, which makes access faster.

    When you create a reference type you receive a reference to the actual object which exists in the heap. There is a small level of indirection whenever you interact with the object itself. These reference types cannot be created on the stack because the lifetime of values in the stack is determined, in great part, by the structure of your code. The function frame of a method call will be popped off the stack when the function returns, for example.

    With value types, however, their copy semantics allows the compiler, depending on where it was created, to place it in the stack. If you create a local variable that holds an instance of a struct in a method and then return it, a copy of it will be created, as Marc explained above. This means that the value can be safely placed in the stack, since the lifetime of the actual instance is tied to the method's function frame. Anytime you send it somewhere outside the current function a copy of it will be created, so it doesn't matter if you tie the existence of the original instance to the scope of the function. Along these lines, you can also see why value types that are captured by closures need to go in the heap: They outlive their scope because they must also be accessible from within the closure, which can be passed around freely.

    If it were a reference type, then you wouldn't be returning a copy of the object, but rather a reference, which means the actual value must be stored somewhere else, otherwise, if you returned the reference and the object's lifetime was tied to the scope in which it was created, it would end up pointing to an empty space in memory.

    The distinction isn't really that "Value types go on the stack, reference types on the heap". The real point is that it's usually more efficient to access objects that live in the stack, so the compiler will try and place those values it can there. It simply turns out that value types, because of their copy semantics, fit the bill better than reference types.

    0 讨论(0)
  • 2020-12-01 03:25

    I believe that whether or not to use stack or heap space is the main distinction between the two, perhaps this article will shed some light on your question: Csharp classes vs structs

    0 讨论(0)
  • 2020-12-01 03:30

    Every process has a data block consists of two different allocatable memory segment. These are stack and heap. Stack is mostly serving as the program flow manager and saves local variables, parameters and returning pointers (in a case of returning from the current working function).

    Classes are very complex and mostly very large types compared to value types like structs (or basic types -- ints, chars, etc.) Since stack allocation should be specialized on the efficiency of program flow, it is not serving an optimal environment to keep large objects.

    Therefore, to greet both of the expectations, this seperated architecture came along.

    0 讨论(0)
  • 2020-12-01 03:34

    (edited to cover points in comments)

    To emphasise: there are differences and similarities between value-types and reference-types, but those differences have nothing to do with stack vs heap, and everything to do with copy-semantics vs reference-semantics. In particular, if we do:

    Foo first = new Foo { Bar = 123 };
    Foo second = first;
    

    Then are "first" and "second" talking about the same copy of Foo? or different copies? It just so happens that the stack is a convenient and efficient way of handling value-types as variables. But that is an implementation detail.

    (end edit)

    Re the whole "value types go on the stack" thing... - value types don't always go on the stack;

    • if they are fields on a class
    • if they are boxed
    • if they are "captured variables"
    • if they are in an iterator block

    then they go on the heap (the last two are actually just exotic examples of the first)

    i.e.

    class Foo {
        int i; // on the heap
    }
    
    static void Foo() {
        int i = 0; // on the heap due to capture
        // ...
        Action act = delegate {Console.WriteLine(i);};
    }
    
    static IEnumerable<int> Foo() {
        int i = 0; // on the heap to do iterator block
        //
        yield return i;
    }
    

    Additionally, Eric Lippert (as already noted) has an excellent blog entry on this subject

    0 讨论(0)
提交回复
热议问题