Some improvements for records with ToString() and formatting #52975
Replies: 2 comments 2 replies
-
This was discussed in LDM 5/3/2021. See upcoming notes. In short, the |
Beta Was this translation helpful? Give feedback.
-
I wish we could remove that Also no need to load builder in each line. just use Append return value? |
Beta Was this translation helpful? Give feedback.
-
This discussion is about a couple ideas for improvements to records in C# 10, both for performance and for better interoperability with the new
InterpolatedStringBuilder
type in .NET 6. Specifically, it pertains to some possible optimizations that could be done to the generatedToString()
method for records, as well as more efficient support for formatting.Faster
ToString()
methodIf we use as an example a record such as
record Person(string FirstName, string LastName, int Age)
, we get this (sharplab):This is not efficient, both because
StringBuilder
doesn't pool the underlying buffer, and for all the various other disadvantages also listed here. It would be much more efficient if the generated code forToString()
on C# 10 leveragedInterpolatedStringBuilder
instead, to get all the benefits such as reduced allocations, no boxing, pooled underlying buffers, etc. I understand that this would also mean thatPrintMembers
could no longer be used (as it just takes aStringBuilder
), so there might be a small code size increase inToString()
that might or might not be a concern, but worth pointing out.Better support for formatting
In the context of the improved string interpolation support in C# 10, I think it'd make sense if records in C# 10 also got an autogenerated
ISpanFormattable
implementation, or some equivalent mechanism to allow them to be used into interpolated string holes with much better efficiency. Having them implementISpanFormattable
seems like the most straightforward option, asInterpolatedStringBuilder
and other types already have explicit support for this interface anyway.Quoting Fred here:
Cheers! 😄
Beta Was this translation helpful? Give feedback.
All reactions