Generics memory management

后端 未结 7 713
慢半拍i
慢半拍i 2021-01-05 02:41

I have question regarding how memory is managed for strong type Generics

List ints1 = new List();
ints1.Add(1); ints1.Add(2); ints1.Add         


        
7条回答
  •  生来不讨喜
    2021-01-05 03:15

    1. List is a reference type no matter how you see it. All these types are allocated on the heap. I do not know whether the C# compiler is clever enough yet to figure out that an object which is not used outside of a method can be allocated on the stack, (Eric Lippert might be able to tell us,) but even if it does, that's something that you, as a programmer, do not need to worry about. It will just be an optimization that the compiler will do for you, without you ever noticing.

    2. An array of int is also a reference type and it is also allocated on the heap, it is just as simple as that. There is no point in wondering about some hypothetical fragmentation of arrays in the stack, because they are simply not allocated in the stack.

提交回复
热议问题