Home

String Interpolation discrepancy

So I decided to boot up Linqpad to do some simple diagnostics on the different ways to format strings. During this, I noticed string interpolation was extremely slow. I originally assumed this was an issue with string interpolation but after running the same code in .NET 5, 4.7.2, and 4.6, it appears to be an issue with Linqpad. I have turned of compiler optimization as well in all environments only to get the same results. Would anyone know what I am potentially missing here that could be causing this discrepancy?

Linqpad run:

.NET 6 run:

var foo = "test1";
var bar = "test2";
var baz = "test3";
var bat = "test4";
var count = 100000000;
var test = string.Empty;
var sw = Stopwatch.StartNew();
for (var i = 0; i < count; i++)
{
    test = foo + bar + baz + bat;
}
Console.WriteLine("Plus: " + sw.ElapsedMilliseconds + "ms");
sw.Restart();

for (var i = 0; i < count; i++)
{
    test = $"{foo}{bar}{baz}{bat}";
}
Console.WriteLine("Interpolation: " + sw.ElapsedMilliseconds + "ms");

Comments

  • I may have discovered the problem. It looks like the IL for interpolation in Linqpad is calling String.Format. The IL for the binary calls String.Concat

  • Presumably you are using LINQPad 5 and not LINQPad 6?

    LINQPad 5 includes the original version of the C# 7.3 compiler (C# 7.3 is the correct C# version for .NET Framework 4.6/4.7/4.8). It seems that they've since improved the C# 7.3 compiler (without incrementing the version number), which is why you're getting a different result in Visual Studio.

    I'll look at updating the compiler in LINQPad 5 to C# 7.3.latest.

  • You are correct. I am using LINQPad 5. I appreciate you looking into this. Also thanks for the info. I've been digging for around trying to figure out why so this helps.

Sign In or Register to comment.