CLR Generics and Struct Boxing
The PR comments from @benaadams here are awesome. https://github.com/dotnet/corefxlab/pull/2358
This is likely basic knowledge needed for high-performance .NET, but it was new to me. Very interesting to see how defining a generic <T> can eliminate boxing/allocations.
Tparameter is explicitly being specified as an interface:
IBufferWriter<byte>; so if you create that
BufferWriter<IBufferWriter<byte>>and give it a struct as the T, then its boxed to the interface and stored in the
BufferWriter<IBufferWriter<byte>>as the boxed
So, if you explicitly specify the T, it will get boxed. If you specify it as a generic, and then call the generic constructor, it will not.
public static JsonWriter<TBufferWriter> Create<TBufferWriter>(
bool prettyPrint = false)
where TBufferWriter : IBufferWriter<byte>
return new JsonWriter<TBufferWriter>(bufferWriter, isUtf8, prettyPrint);