String Concat using constants - performance

前端 未结 2 913
时光取名叫无心
时光取名叫无心 2020-12-21 02:36

Assume I have the following string constants:

const string constString1 = \"Const String 1\";
const string constString2 = \"Const String 2\";
const string co         


        
相关标签:
2条回答
  • 2020-12-21 03:06

    The first one will be done by the compiler (at least the Microsoft C# Compiler) (in the same way that the compiler does 1+2), the second one must be done at runtime. So clearly the first one is faster.

    As an added benefit, in the first one the string is internalized, in the second one it isn't.

    And String.Format is quite slow :-) (read this http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/formatting-strings.aspx). NOT "slow enough to be a problem", UNLESS all your program do all the day is format strings (MILLIONS of them, not TENS). Then you could probably to it faster Appending them to a StringBuilder.

    0 讨论(0)
  • 2020-12-21 03:09

    The first variant will be best, but only when you are using constant strings.

    There are two compilator optimizations (from the C# compiler, not the JIT compiler) that are in effect here. Lets take one example of a program

    const string A = "Hello ";
    const string B = "World";
    
    ...
    string test = A + B;
    

    First optimization is constant propagation that will change your code basically into this:

    string test = "Hello " + "World";
    

    Then a concatenation of literal strings (as they are now, due to the first optimization) optimization will kick in and change it to

    string test = "Hello World";
    

    So if you write any variants of the program shown above, the actual IL will be the same (or at least very similar) due to the optimizations done by the C# compiler.

    0 讨论(0)
提交回复
热议问题