String.Intern 方法只是将对字符串的引用添加到实习生池中,还是创建字符串的副本?

Does String.Intern method just add a reference to a string to the intern pool or it creates a copy of the string?

假设我有一个字符串'str'。我想使用 String.Intern 方法实习。我只是想知道,在 'str' 的值尚未被保留的情况下,String.Intern 到底是如何工作的。 来自documentation的方法描述如下:

The Intern method uses the intern pool to search for a string equal to the value of str. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to str is added to the intern pool, then that reference is returned.

但是“CLR via C#”一书中的这段摘录却有不同的说法:

Intern, takes a String, obtains a hash code for it, and checks the internal hash table for a match. If an identical string already exists, a reference to the already existing String object is returned. If an identical string doesn’t exist, a copy of the string is made, the copy is added to the internal hash table, and a reference to this copy is returned.

我想文档中的描述是正确的。那么,只将str的引用添加到实习生池中,而不复制字符串对象?

这很容易直接测试:

// Make string from char[] to ensure it's not already interned
string s1 = new string(new[] { 'H', 'e', 'l', 'l', 'o' });
string i1 = string.Intern(s1);
bool result1 = object.ReferenceEquals(s1, i1);

string s2 = new string(new[] { 'H', 'e', 'l', 'l', 'o' });
string i2 = string.Intern(s2);
bool result2 = object.ReferenceEquals(s2, i2);

注意result1设置为true,说明原来的string对象没有被复制。另一方面,result2设置为false,表明在实习生池中找到了第二个构造的string对象"Hello",因此string.Intern()方法 returns interned instance instead of the new constructed instance passed in.

string.Intern()方法不复制字符串。它只是检查传递的引用是否等于池中已有的字符串,如果不是,则将其添加到池中。