)
The difference in efficiency here is incredible. Let??™s look at the ArrayList first,
considering 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 top
of that, you??™ve got all the references themselves, each of which takes up 4 bytes. So for
each byte of useful data, we??™re paying at least 16 bytes??”and then there??™s the extra
unused space for references in the buffer.
Compare this with the List
. Each byte in the list takes up a single byte
within the elements array. There??™s still ???wasted??? space in the buffer, waiting to be used
potentially by new items??”but at least we??™re only wasting a single byte per unused element
there.
We don??™t just gain space, but execution speed too. We don??™t need the time taken to
allocate the box, the type checking involved in unboxing the bytes in order to get at
them, 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 find things happening transparently
on our behalf, however. C# has always made life easier with syntactic shortcuts,
and our next section looks at a familiar example but with a generic twist: iterating
with foreach.
8 When running on a 64-bit CLR, the overheads are bigger.
5
3
15
10
12
13
.
Pages:
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196