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?
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.
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