1

An array in C# has some space overhead: it stores its sync block, its array type, possibly its element type (for reference types), its length...

Some quick tests indicate that the array's elements actually start at a cache line boundary. For example, in a byte[] it is faster for two separate threads to simultaneously update index 63 and 64, respectively (as they are on different cache lines), than for them to update index 62 and 63 (as they are on the same cache line).

I'm curious to know where the metadata is stored. Does it go at the end, possibly residing in the same cache line as the last few elements? Or is it stored elsewhere altogether?

This could be useful when trying to cache-optimize the usage of some array. If the metadata is stored in a separate cache line, then there is probably nothing we can do to avoid that extra cache line fill whenever the array is used. However, if it is stored in the last cache line, then the array size could be optimized to leave precisely enough room for the metadata, and the elements in that cache line could be probed first, as it is available anyway.

Timo
  • 7,992
  • 4
  • 49
  • 67
  • 1
    Related: https://stackoverflow.com/questions/487202/memory-layout-of-a-net-array – canton7 Mar 13 '19 at 16:31
  • 1
    Are you sure that you didn't just get lucky with hitting the cache line boundary? Try allocating a small (4-element, say) array, and then allocate your test array straight after. – canton7 Mar 13 '19 at 16:33
  • 1
    thinking aloud: if the metadata wasn't at the start, then in order to find the metadata, it would first need to know the size so it can compute the offset of the metadata, so ... a prerequisite for getting the metadata would be... the metadata – Marc Gravell Mar 13 '19 at 17:23
  • @MarcGravell You make an excellent point. xD – Timo Mar 14 '19 at 15:16

0 Answers0