[API Proposal]: Consider Equals method(s) on DefaultInterpolatedStringHandler to avoid temporary string allocations #110427
Labels
api-suggestion
Early API idea and discussion, it is NOT ready for implementation
area-System.Runtime
untriaged
New issue has not been triaged by the area owner
Background and motivation
Was just modifying some code and noticed it was creating a string from a number and adding it to other strings in an if statement just to compare to another string and then throw the just created string away. Started updating the code to remove the number allocation by using string interpolation, and then realized the interpolated string is still being allocated just to do a comparison and then thrown away. It seems a bit silly when we could do span comparisons to avoid the string allocation.
If this API was added, Roslyn would also want to update to generate code that makes use of the API as most people aren't going to be using
DefaultInterpolatedStringHandler
explicitly.API Proposal
API Usage
Ideally Roslyn generated diff:
Alternative Designs
public ref struct DefaultInterpolatedStringHandler { + public bool EqualsAndClear(ReadOnlySpan<char> other, StringComparison comparisonType); }
Risks
DefaultInterpolatedStringHandler
uses an array pool internally and returns the array to the pool when the string is realized. Separating the usage of the interpolated string from the clearing makes the type more error prone, so the alternative design follows the currentToStringAndClear
public method where it combines the action and clearing the array.The text was updated successfully, but these errors were encountered: