String Interpolation vs String.Format

前端 未结 4 902
天命终不由人
天命终不由人 2020-12-02 18:00

Is there a noticable performance difference between using string interpolation:

myString += $\"{x:x2}\";

vs String.Format()?



        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 18:38

    The answer is both yes and no. ReSharper is fooling you by not showing a third variant, which is also the most performant. The two listed variants produce equal IL code, but the following will indeed give a boost:

    myString += $"{x.ToString("x2")}";
    

    Full test code

    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Configs;
    using BenchmarkDotNet.Diagnosers;
    using BenchmarkDotNet.Diagnostics.Windows;
    using BenchmarkDotNet.Running;
    
    namespace StringFormatPerformanceTest
    {
        [Config(typeof(Config))]
        public class StringTests
        {
            private class Config : ManualConfig
            {
                public Config() => AddDiagnoser(MemoryDiagnoser.Default, new EtwProfiler());
            }
    
            [Params(42, 1337)]
            public int Data;
    
            [Benchmark] public string Format() => string.Format("{0:x2}", Data);
            [Benchmark] public string Interpolate() => $"{Data:x2}";
            [Benchmark] public string InterpolateExplicit() => $"{Data.ToString("x2")}";
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var summary = BenchmarkRunner.Run();
            }
        }
    }
    

    Test results

    |              Method | Data |      Mean |  Gen 0 | Allocated |
    |-------------------- |----- |----------:|-------:|----------:|
    |              Format |   42 | 118.03 ns | 0.0178 |      56 B |
    |         Interpolate |   42 | 118.36 ns | 0.0178 |      56 B |
    | InterpolateExplicit |   42 |  37.01 ns | 0.0102 |      32 B |
    |              Format | 1337 | 117.46 ns | 0.0176 |      56 B |
    |         Interpolate | 1337 | 113.86 ns | 0.0178 |      56 B |
    | InterpolateExplicit | 1337 |  38.73 ns | 0.0102 |      32 B |
    

    The InterpolateExplicit() method is faster since we now explicitly tell the compiler to use a string. No need to box the object to be formatted. Boxing is indeed very costly. Also, note that we reduced the allocations a bit.

提交回复
热议问题