Is there any performance increase by changing this .NET string to a const? Does the IL automatically do that?

前端 未结 4 1144
深忆病人
深忆病人 2021-01-24 13:07

Given the following simple .NET code, is there any difference between these two, under the hood with respect to the string \"xml\"?

if (extension.Eq         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-24 13:50

    Even more awesome, is that if there's another "xml" string used in another place, the compiler will only make one const creation and both of those references will refer to that single string reference/memory alloc.

    This is normal behavior since .NET make "string interning" by default so many variables will references the same memory allocation

    So .NET automatically performs string interning for all string literals. This is done by means of an intern pool – a special table that stores references to all unique strings.

    Only explicitly declared string literals are interned on the compile stage. The strings created at runtime are not checked for being already added to the pool. For example:

    Interning example

    string s="AB";   //will be interned  
    string s1 ="C";    
    string s2 = s1+s2  //will not be interned 
    

    For your first question no there is no differences since at compilation time the compiler can make a smart decision of replacing the variable by the content since const is hardcoded which make a better performance so you will not see any performance increase.

提交回复
热议问题