Where Are Value Types Stored In (C#) Generic Collections

后端 未结 5 1740
北海茫月
北海茫月 2021-02-08 09:31

It is true that generic collections perform better than non-generic collections for value types. (i.e. List vs. ArrayList).

But why is that, other than the boxing-unboxi

5条回答
  •  臣服心动
    2021-02-08 10:03

    The relevant implementation detail is that the underlying storage for a List is a T[]. So for a List the values will be stored in an int[]. The integers are stored in a contiguous chunk of memory, allocated from the garbage collected heap.

    What makes it so fast is not just that the integers are not boxed, it is that an int[] works so very well with the CPU cache. When you read the first element, you essentially get the next 15 for free without having to read the slow RAM or secondary cache. This works not nearly so well for a boxed int because it is so large and the extra reference can have poor cache locality. However, the garbage collector really helps to take the sting out of that cost by compacting the heap.

提交回复
热议问题