Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The main advantage I can think of for using arrays in generic classes is to avoid boxing. Specifically, when you cast a value type (a "primitive" such as Int32, Boolean, etc.) to an object, the runtime has to wrap the value type instance in a reference type ("box" it) and place it on the managed heap. That makes accessing value types as reference types much less efficient than accessing them directly as value types.</p> <p>If you have a</p> <pre><code>class MyGenericContainer&lt;T&gt; { private T[] array; } </code></pre> <p>and you instantiate <code>MyGenericContainer&lt;int&gt;</code>, you'll get an array of int instances, which won't be boxed when you access them.</p> <p>On the other hand, if you had</p> <pre><code>class MyContainer { private object[] array; } </code></pre> <p>even though you can certainly add an integer to the array, it would be boxed, and therefore access to it will be less efficient, and the act of storing it involves more storage. To be specific, each array will store a reference (4 bytes?) to its item. In the generic case when parameterized with a value type, the pointer will point to a value type that exists as a field within the parent object on the managed heap. In the non-generic case, the pointer will reference an object wrapper within the parent object on the managed heap, which will internally reference the value type instance somewhere else on the heap. So, you get the overhead of an additional object and reference when boxing value types. Accesses also involve more overhead, but it's complicated depending on the particular use case.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload