Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Generics provide performance and runtime-memory advantages over non-generic equivalents. For example, compare the following.</p> <pre><code>ArrayList arrayList = new ArrayList(new Byte[] { 1, 2, 3, 4, 5, 6, 7, 8} ); </code></pre> <p>vs</p> <pre><code>List&lt;Byte&gt; byteList = new List&lt;Byte&gt; { 1, 2, 3, 4, 5, 6, 7, 8 }; </code></pre> <p>The ArrayList will contain an internal storage of object[] which with each element pointing to a byte. The ideal memory for this part of the list with 32 bit pointers is therefore 8 * 4 + 8 = 40 bytes. I say ideal 'cause it's actually worse since the boxed bytes will have some additional overhead, although I don't know exactly how much. </p> <p>The List implementation will instead contain byte[] which will require just one pointer to the array plus the 8 bytes, for a total of 12 bytes of memory without the boxing overhead, whatever that is.</p> <p>In addition to the memory differences, there is also the performance cost of boxing/unboxing the values.</p> <p>The difference is less for reference types, but even there you'll have a cost penalty for casting constantly when taking data out of the non-generic type.</p> <p>These differences are real, but will have immeasurable impact on most applications. The real advantage of generics is greater reliability of compile-time verification and simpler code that results from using typed values.</p> <p>In my opinion it's best to use generics whenever appropriate and possible.</p> <p>Sam</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