Memory usage of concatenating strings using interpolated vs “+” operator

后端 未结 4 922
无人共我
无人共我 2021-01-01 15:36

I see the benefit of using interpolated strings, in terms of readability:

string myString = $\"Hello { person.FirstName } { person.LastName }!\"
4条回答
  •  别那么骄傲
    2021-01-01 15:55

    I made a simple test, see below. If you concatenate constants, don't use "string.Concat" because the compiler can't concatenate your strings at compile time. If you use variables, the results are effectively the same.

    time measure results:

    const string interpolation : 4
    const string concatenation : 58
    const string addition      : 3
    var string interpolation   : 53
    var string concatenation   : 55
    var string addition        : 55
    mixed string interpolation : 47
    mixed string concatenation : 53
    mixed string addition      : 42
    

    the code:

    void Main()
    {
    
    const int repetitions = 1000000; 
    const string part1 = "Part 1"; 
    const string part2 = "Part 2"; 
    const string part3 = "Part 3"; 
    var vPart1 = GetPart(1); 
    var vPart2 = GetPart(2); 
    var vPart3 = GetPart(3); 
    
    Test("const string interpolation ", () => $"{part1}{part2}{part3}"); 
    Test("const string concatenation ", () => string.Concat(part1, part2, part3)); 
    Test("const string addition      ", () => part1 + part2 + part3); 
    Test("var string interpolation   ", () => $"{vPart1}{vPart2}{vPart3}"); 
    Test("var string concatenation   ", () => string.Concat(vPart1, vPart2, vPart3)); 
    Test("var string addition        ", () => vPart1 + vPart2 + vPart3); 
    Test("mixed string interpolation ", () => $"{vPart1}{part2}{part3}");
    Test("mixed string concatenation ", () => string.Concat(vPart1, part2, part3));
    Test("mixed string addition      ", () => vPart1 + part2 + part3);
    
    void Test(string info, Func action) 
    { 
        var watch = Stopwatch.StartNew(); 
        for (var i = 0; i < repetitions; i++) 
        { 
            action(); 
        } 
        watch.Stop(); 
        Trace.WriteLine($"{info}: {watch.ElapsedMilliseconds}"); 
    } 
    
    string GetPart(int index) 
        => $"Part{index}"; 
    
    }
    

提交回复
热议问题