简体   繁体   English

.NET中集合的内存分配

[英]Memory allocation for collections in .NET

This might be a dupe. 这可能是一个骗局。 I did not find enough information on this. 我没有找到足够的信息。

I was discussing memory allocation for collections in .Net. 我正在讨论.Net中集合的内存分配。 Where is the memory for elements allocated in a collection? 集合中分配的元素的内存在哪里?

List<int> myList = new List<int>();

The variable myList is allocated on stack and it references the List object created on heap. 变量myList在堆栈上分配,它引用在堆上创建的List对象。

The question is when int elements are added to the myList, where would they be created ? 问题是当int元素添加到myList时,它们会在哪里创建?

Can anyone point the right direction? 谁能指出正确的方向?

The elements will be created on the heap. 元素将在堆上创建。 The only thing that lives on the stack is the pointer (reference) to the list ( List<> is a reference type) 生活在堆栈上的唯一东西是列表的指针(引用)( List<>是引用类型)

The elements will also reside in the heap (in an array, that's how List works internally). 元素也将驻留在堆中(在数组中,这就是List在内部的工作方式)。

In principle, only local variables and arguments are be allocated on the stack and everything else goes on the heap (unless you use rare things such as stackalloc , but you don't need to worry about that) 原则上,只有局部变量和参数在堆栈上分配,其他所有内容都在堆上(除非你使用稀有的东西,比如stackalloc ,但你不需要担心)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM