While reading through the source code of Roslyn on GitHub, I noticed the much used ObjectPool<T>
class. It is used to reduce memory overhead.
Internally it uses an array to store the pooled objects.
What I don't understand is why it uses a private struct called Element
containing a single field of type T
as array element, instead of just using T
.
Is this out of concern for performance? Memory overhead?
It may be for performance reasons. See this article by Jon Skeet.
To summarize, value type arrays are invariant in C#, which means the runtime can avoid doing a compatibility check when storing items in the array. In the article, Mr. Skeet uses a wrapper structure similar to the one you described and shows an improvement in write performance to the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With