Skip to content

Latest commit

 

History

History
87 lines (61 loc) · 2.68 KB

File metadata and controls

87 lines (61 loc) · 2.68 KB

U2U1105: Do not use string interpolation to concatenate strings

Category : Performance

Severity : Warning

Cause

String interpolation is used to concatenate strings.

Rule Description

String interpolation is very powerful, but using it to concatenate strings is not only overkill, it is highly inefficient.

UPDATE: Starting with Visual Studio 2017 version 15.8, the compiler does the optimization automatically.

How to Fix Violations

Use the code fix to convert the interpolation to a concatenation.

Example

Consider this BenchmarkDotNet benchmark:

public class ToMeasure
{
    string s1 = "abc";
    string s2 = "def";

    [Benchmark]
    public void StringFormat()
    {
        string s = string.Format("{0}/{1}", s1, s2);
    }

    [Benchmark]
    public void Interpolation()
    {
        string s = $"{s1}/{s2}";
    }

    [Benchmark(Baseline = true)]
    public void Concatenation()
    {
        string s = s1 + "/" + s2;
    }
}

This is the result summary on one of our test machines:

BenchmarkDotNet=v0.10.6, OS=Windows 10 Redstone 1 (10.0.14393)
Processor=Intel Core i7 CPU 860 2.80GHz (Nehalem), ProcessorCount=8
Frequency=2727695 Hz, Resolution=366.6099 ns, Timer=TSC
  [Host]     : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
  DefaultJob : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0


        Method |      Mean |     Error |    StdDev | Scaled | ScaledSD |
-------------- |----------:|----------:|----------:|-------:|---------:|
  StringFormat | 145.37 ns | 0.4084 ns | 0.3820 ns |   5.22 |     0.01 |
 Interpolation | 146.79 ns | 0.4387 ns | 0.3889 ns |   5.28 |     0.02 |
 Concatenation |  27.83 ns | 0.0490 ns | 0.0382 ns |   1.00 |     0.00 |

All three methods do the same thing, but in this example using string interpolation is over five times slower than just concatenating the strings.

Notice also that the performance of the string interpolation is the same as when calling string.Format. The reason is of course that string interpolation compiles to string.Format calls, as is evidenced by this IL:

.method public hidebysig instance void Interpolation () cil managed 
{
    .maxstack 8

    ldstr "{0}/{1}"
    ldarg.0
    ldfld string Benchmark.ToMeasure::s1
    ldarg.0
    ldfld string Benchmark.ToMeasure::s2
    call string [mscorlib]System.String::Format(string, object, object)
    pop
    ret
}

Related Rules

U2U1104 Do not use composite formatting to concatenate strings

© 2017 U2U Consult