Roslyn ObjectPool structural shell

I am considering a Roslyn ObjectPool implementation ( https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/SharedCollections/ObjectPool%601.cs ) and I donโ€™t understand why they didnโ€™t just decide to have an array T instead of wrap T inside the structure?

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

What is the purpose of this?

+7
arrays generics c # struct roslyn
source share
2 answers

This is a general trick to avoid performance issues when setting array elements that are reference types. Arrays are options on the CLR (and on the JVM). You can write string in object[] . This requires a run-time check that you are not actually storing the string in SomethingElse[] . When using this type of thread, this check is not required to be performed at run time.

+5
source share

I believe this is for performance reasons. The structure array is a garbage collector friend, not a class array.

Out of 5 Tips and Techniques to Prevent GC Auto Build

With an array of class instances, the GC must check each element in this array to see if it is a living object or not (the same is true for general collections that use an internal array). With an array of structs, GC just looks to see if the array itself will still live, since the structs cannot be null (this is even true for Incorrect structures that simply use an internal tracking mechanism to determine invalid). So these are potentially thousands or even millions of elements that the GC does not need to check when starting the collection!

+1
source share

All Articles