Implementing ISpanFormattable
04/14/2024
I have recently realized that implementing the ISpanFormattable
interface enables a type to participate in string interpolation feature of C# in a more efficient way. This realization made me curious how much more efficient it is to implement the corresponding public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = default)
method to the standard ToString()
. In this blog post I use .NET8 and C# 12.
Implementing ISpanFormattable is not automatically justified for all types, but ones that participate in frequent serialization, such as string interpolation. One can search the types that implement this interface, and it contains most of the primitive and value types (int
, Guid
, DateTime
, etc).
Fortunately I just have one such type on hand that lends itself for the investigation. In a previous blog post, I iterated through a couple of different implementation of FractionalDouble
type.
While understanding the details of the FractionalDouble
format is less relevant for this post, here is a quick summary: