13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Advanced generics89ArrayListobject[]BoxedbytesListbyte[]elementsref5elements5refrefref3ref315countref15count106refref106121312......13Figure 3.3 Visual demonstration of why List takes up a lot less space than ArrayListwhen stor<strong>in</strong>g value typesList and ArrayList have a buffer, and they create a larger buffer when theyneed to.)The difference <strong>in</strong> efficiency here is <strong>in</strong>credible. Let’s look at the ArrayList first,consider<strong>in</strong>g a 32-bit CLR. 8 Each of the boxed bytes will take up 8 bytes of object overhead,plus 4 bytes (1 byte, rounded up to a word boundary) for the data itself. On topof that, you’ve got all the references themselves, each of which takes up 4 bytes. So foreach byte of useful data, we’re pay<strong>in</strong>g at least 16 bytes—and then there’s the extraunused space for references <strong>in</strong> the buffer.Compare this with the List. Each byte <strong>in</strong> the list takes up a s<strong>in</strong>gle bytewith<strong>in</strong> the elements array. There’s still “wasted” space <strong>in</strong> the buffer, wait<strong>in</strong>g to be usedpotentially by new items—but at least we’re only wast<strong>in</strong>g a s<strong>in</strong>gle byte per unused elementthere.We don’t just ga<strong>in</strong> space, but execution speed too. We don’t need the time taken toallocate the box, the type check<strong>in</strong>g <strong>in</strong>volved <strong>in</strong> unbox<strong>in</strong>g the bytes <strong>in</strong> order to get atthem, or the garbage collection of the boxes when they’re no longer referenced.We don’t have to go down to the CLR level to f<strong>in</strong>d th<strong>in</strong>gs happen<strong>in</strong>g transparentlyon our behalf, however. <strong>C#</strong> has always made life easier with syntactic shortcuts,and our next section looks at a familiar example but with a generic twist: iterat<strong>in</strong>gwith foreach.8When runn<strong>in</strong>g on a 64-bit CLR, the overheads are bigger.Licensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!