0

In Rider Resharper suggests to simplify string interpolation.

Reshaper Suggestion

When doing so, the Heap Allocation Viewer plugin warns me about boxing allocation. And indeed, the IL code is different and when running a stopwatch it's clear that the simplified approach is approximately 50% slower.

Boxing Allocation

Two questions:

  1. Why does Rider suggest this "improvement" when in reality it doesn't result in the same and even less performant code.
  2. Why doesn't the compiler convert :X8 to ToString(x8) to improve performance? Is there any advantage of :X8?
public string ToHexString1() => $"HexValue is: {uintVariable.ToString("X8")}"; //no boxing allocation
public string ToHexString2() => $"HexValue is: {uintVariable:X8}"; //boxing allocation
2
  • 1
    Which version of .NET is this? Newer versions uses the new string interpolation handlers so no boxing should be happening Commented Apr 3, 2024 at 21:01
  • Ah sorry, should have mentioned the .NET version. It's .NET Framework 4.7.1. Can't change it because I work with Unity and therefore the .NET version is fixed. Commented Apr 3, 2024 at 21:08

1 Answer 1

1

Primarily because it's simpler code. You shouldn't worry about boxing allocations unless you are in a tight loop. It's just not worth thinking about. Write code that's easy to understand, and optimize where necessary.

However, in .NET 6+ this is actually better. You can see the decompilation in SharpLab gives you:

DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(13, 1);
defaultInterpolatedStringHandler.AppendLiteral("Hex Value is ");
defaultInterpolatedStringHandler.AppendFormatted(i, "X8");
return defaultInterpolatedStringHandler.ToStringAndClear();

which has no boxing.

Whereas in .NET Framework you get:

return string.Format("Hex Value is {0:X8}", i);

which boxes i.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.