Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn ObjectPool struct wrapper

I am looking at the Roslyn ObjectPool implementation ( https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/SharedCollections/ObjectPool%601.cs ) and I don't get why they did not simply choose to have an array of T but instead wrap T inside a struct?

[DebuggerDisplay("{Value,nq}")] 
private struct Element 
{ 
    internal T Value; 
} 
...
private readonly Element[] _items;

What is the purpose of this?

like image 568
Thomas Zeman Avatar asked Sep 17 '15 10:09

Thomas Zeman


1 Answers

This is a common trick to avoid performance problems when setting array items that are reference types. Arrays are variant on the CLR (and on the JVM). You can write a string into an object[]. This requires a runtime check that you are not actually storing a string into a SomethingElse[]. With that value type trick it's not necessary to perform that check at runtime.

like image 151
usr Avatar answered Sep 20 '22 13:09

usr