Skip to content

Instantly share code, notes, and snippets.

@stjeong
Last active July 23, 2023 23:18
Show Gist options
  • Save stjeong/22d5f3c3e9cab440a312bd691157e012 to your computer and use it in GitHub Desktop.
Save stjeong/22d5f3c3e9cab440a312bd691157e012 to your computer and use it in GitHub Desktop.
C# 10 - string interpolation
// Refer to tweet - https://twitter.com/Dave_DotNet/status/1682699744747958274
// This code allocates same 72 bytes in GC Heap.
// However this may be slower than string.Create, because DefaultInterpolatedStringHandler is made for more general purpose.
// C# 10+ and .NET 6+
string title = "Mr.";
string first = "David";
string middle = "Patrick";
string last = "Callan";
{
string text = $"{title} {first} {middle} {last}"; // 72 bytes in GC Heap
}
// Upper code is translated as follows by Roslyn compiler
{
DefaultInterpolatedStringHandler d = new DefaultInterpolatedStringHandler(3, 4);
d.AppendFormatted(title);
d.AppendLiteral(" ");
d.AppendFormatted(first);
d.AppendLiteral(" ");
d.AppendFormatted(middle);
d.AppendLiteral(" ");
d.AppendFormatted(last);
string text = d.ToStringAndClear();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment