开发者

In c# when an int is stored in a List<int> or int[] is that int still on the stack or is it boxed/moved to the heap?

开发者 https://www.devze.com 2023-03-21 18:30 出处:网络
I understand int\'s, as are all value types, are stored on the stack. Int\'s can be boxed into objects whi开发者_StackOverflowch then means the int is storage on the heap. BUT what happens when an int

I understand int's, as are all value types, are stored on the stack. Int's can be boxed into objects whi开发者_StackOverflowch then means the int is storage on the heap. BUT what happens when an int is stored in a List or int[]?

I know List ofT is a class/reference type/heap stored type - does this mean int's in a List are boxed onto the heap?

Thanks


No boxing is necessary when working with the generic List<int> type.


It is not boxed if it is stored in a typed List

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

"If a value type is used for type T, the compiler generates an implementation of the List class specifically for that value type. That means a list element of a List object does not have to be boxed before the element can be used, and after about 500 list elements are created the memory saved not boxing list elements is greater than the memory used to generate the class implementation."


I know List ofT is a class/reference type/heap stored type - does this mean int's in a List are boxed onto the heap?

Placing an int in storage that is allocated on the heap is not the same as boxing that int.

Boxing is when the int is individually placed in its own object wrapper. This doesn't happen in a generic List<int>, but would happen in an ArrayList.

http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号