Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 432
Wazner Avatar asked Jul 29 '15 19:07

Wazner


1 Answers

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.

like image 93
Kyle Avatar answered Oct 10 '22 00:10

Kyle