Search code examples
c#performancestring-interpolation

Is there a run-time overhead to using string interpolation to insert a constant?


I have a class which has 3 methods, each method starts a new System.Diagnostics.Process where some unique arguments are passed in along with some standard ones shared by all 3.

In order to reduce duplication I currently have all the consistent arguments stored as a class-level constant and then interpolate them in as the method runs.

private const string File = "file.exe";
private const string StandardAgs = "--whatever";

public void DoA()
{
    string command = $"{File} unique args for A {StandardAgs}";
    Process.Start(command);
}

public void DoB()
{
    string command = $"{File} unique args for B {StandardAgs}";
    Process.Start(command);
}

public void DoC()
{
    string command = $"{File} unique args for C {StandardAgs}";
    Process.Start(command);
}

Is there a run-time processing overhead to this interpolation? Or, because all the class-level variables are constants, will the compiler recognise that they can be interpolated at compile-time?

Failing that, would I need to have all my strings be constant to achieve zero run-time interpolation, like so?

private const string File = "file.exe";
private const string StandardAgs = "--whatever";

private const string Acommand = $"{File} unique args for A {StandardAgs}";
private const string Bcommand = $"{File} unique args for B {StandardAgs}";
private const string Ccommand = $"{File} unique args for C {StandardAgs}";

public void DoA()
{
    Process.Start(Acommand);
}

public void DoB()
{
    Process.Start(Bcommand);
}

public void DoC()
{
    Process.Start(Ccommand);
}

I recognise that only second example stores the strings statically in memory rather than on a per-instance basis but I'm not concerned about the memory footprint, only how much string interpolation occurs at run-time.


Solution

  • I wrote a short program and then run it through ILSpy.

    c#:

    const string Foo = "Hello";
    
    static void Main()
    {
        var bar = $"{Foo}Bar!";
        Console.WriteLine(bar);
    }
    

    IL:

    IL_0001: ldstr "{0}Bar!"
    IL_0006: ldstr "Hello"
    IL_000b: call string [mscorlib]System.String::Format(string, object)
    IL_0010: stloc.0
    IL_0011: ldloc.0
    IL_0012: call void [mscorlib]System.Console::WriteLine(string)
    

    Looks like it turns into a string.Format call and gets computed at runtime.

    So yes, there is a (very very small) performance impact.