Reputation: 910
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?
Upvotes: 8
Views: 414
Reputation: 73482
I believe it is for performance reasons. Array of struct is a friend to garbage collector as opposed to Array of class.
From 5 Tips and Techniques for Avoiding Automatic GC Collections
With an array of class instances, the GC has to check each item in that array to see if it is a live object or not (the same is true for generic collections, which use an internal array). With an array of structs, the GC just looks to see if the array itself is still a live object, since structs cannot be null (this is true even for Nullable structs, which just use an internal tracking mechanism to determine nullity). So that is potentially thousands or even millions of items that the GC does not need to examine when a collection runs!
Upvotes: 1
Reputation: 171218
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.
Upvotes: 5