简体   繁体   English

为什么泛型会减少装箱/拆箱操作

[英]Why generics reduces boxing/unboxing operations

From here 这里

// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();

// No boxing, no casting:
list1.Add(3);    

I understand there is no casting. 我了解没有强制转换。 But why no boxing happens? 但是为什么没有拳击发生呢?

"3" is on stack and list is in heap. “ 3”在堆栈上,列表在堆中。

How it happens that value from stack moved to heap without boxing? 将值从堆栈移动到堆而无需装箱的情况如何?

What happens under the hood? 引擎盖下会发生什么?

Boxing doesn't happen here because the array that backs the List is T[] , not object[] . 这里没有装箱,因为支持List的数组是T[] ,而不是object[] Therefore, the runtime knows your items are integers and doesn't need to box them. 因此,运行时知道您的项目是整数,不需要将它们装箱。

List在堆上已经有一个预先分配的int数组,因此只需要将其中一个int更改为3。

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

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