Why some identical strings are not interned in .NET?

后端 未结 5 1541
悲&欢浪女
悲&欢浪女 2020-12-21 00:17
string s1 = \"test\";
string s5 = s1.Substring(0, 3)+\"t\"; 
string s6 = s1.Substring(0,4)+\"\";   
Console.WriteLine(\"{0} \", object.ReferenceEquals(s1, s5)); //Fa         


        
5条回答
  •  無奈伤痛
    2020-12-21 01:13

    The CLR doesn't intern all strings. All string literals are interned by default. The following, however:

    Console.WriteLine("{0} ", object.ReferenceEquals(s1, s6)); //True
    

    Returns true, since the line here:

    string s6 = s1.Substring(0,4)+"";  
    

    Is effectively optimized to return the same reference back. It happens to (likely) be interned, but that's coincidental. If you want to see if a string is interned, you should use String.IsInterned()

    If you want to intern strings at runtime, you can use String.Intern and store the reference, as per the MSDN documentation here: String.Intern Method (String). However, I strongly suggest you not use this method, unless you have a good reason to do so: it has performance considerations and potentially unwanted side-effects (for example, strings that have been interned cannot be garbage collected).

提交回复
热议问题