Wazner
Wazner

Reputation: 3102

Why does roslyn wrap objects in structures when put in arrays?

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?

Upvotes: 11

Views: 220

Answers (1)

Kyle
Kyle

Reputation: 6684

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.

Upvotes: 14

Related Questions