Skip to content

[API Proposal]: Consider Equals method(s) on DefaultInterpolatedStringHandler to avoid temporary string allocations #110427

@BrennanConroy

Description

@BrennanConroy

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

namespace System.Runtime.CompilerServices;

public ref struct DefaultInterpolatedStringHandler
{
+    public bool Equals(ReadOnlySpan<char> other, StringComparison comparisonType);
-    internal void Clear();
+    public void Clear();
}

API Usage

var str1 = "somevalue";
var str2 = "some";
var val1 = 1;
if (str1 == $"{str2}{val1}")
{
}

Ideally Roslyn generated diff:

string text = "somevalue";
string value = "some";
int value2 = 1;
DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(0, 2);
defaultInterpolatedStringHandler.AppendFormatted(value);
defaultInterpolatedStringHandler.AppendFormatted(value2);
-bool flag = defaultInterpolatedStringHandler.ToStringAndClear() == text;
+bool flag = defaultInterpolatedStringHandler.Equals(text, StringComparison.InvariantCulture);
+defaultInterpolatedStringHandler.Clear();

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 current ToStringAndClear public method where it combines the action and clearing the array.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions