Optimize temporary string usage when DefaultInterpolatedStringHandler is used
- Dominant language
- C#
- Stars
- 20.7k
- Forks
- 4.3k
- PR merge metrics
- PR metrics pending
Description
**Version Used**:
.NET 10
**Steps to Reproduce**:
Today, the compiler generates code using `DefaultInterpolatedStringHandler` for various scenarios, I don't know all the places it's used and whether they might benefit from updates, so I'll focus on the one I do know.
Given the following simplified code
```csharp
var str1 = "somevalue";
var str2 = "some";
var val1 = 1;
if (str1 == $"{str2}{val1}")
{
}
```
The compiler generates:
```csharp
string value = "some";
int value2 = 1;
DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(0, 2);
defaultInterpolatedStringHandler.AppendFormatted(value);
defaultInterpolatedStringHandler.AppendFormatted(value2);
bool flag = "somevalue" == defaultInterpolatedStringHandler.ToStringAndClear();
```
The issue is that `defaultInterpolatedStringHandler.ToStringAndClear()` allocates a string just to do a string comparison, which should be allocation free if we could access the underlying `ReadOnlySpan`.
With https://github.com/dotnet/runtime/pull/112171 being merged, we now have access the the underlying `ReadOnlySpan` and a way to clear the pooled memory when we're done with the string handler.
It would be nice if the compiler could now generate the allocation free code:
```csharp
string value = "some";
int value2 = 1;
DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(0, 2);
defaultInterpolatedStringHandler.AppendFormatted(value);
defaultInterpolatedStringHandler.AppendFormatted(value2);
bool flag = "somevalue" == defaultInterpolatedStringHandler.Text;
defaultInterpolatedStringHandler.Clear();
```
Resulting in free perf for all!
Contributor guide
Assessment
This issue has not been assessed yet.