简体   繁体   English

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?

Suppose I have a string 'str'.假设我有一个字符串'str'。 I want to intern it using String.Intern method.我想使用 String.Intern 方法对其进行实习。 I just wonder, how exactly String.Intern works in case when value of 'str' hasn't been interned yet.我只是想知道,如果'str' 的值尚未被实习,String.Intern 究竟是如何工作的。 The description of the method from documentation is following: 文档中对该方法的描述如下:

The Intern method uses the intern pool to search for a string equal to the value of str. Intern 方法使用实习池来搜索等于 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.如果字符串不存在,则将对 str 的引用添加到实习池,然后返回该引用。

But this excerpt from a book "CLR via C#" tells differently:但是这本书摘自“CLR via C#”这本书的摘录不同:

Intern, takes a String, obtains a hash code for it, and checks the internal hash table for a match. Intern 获取一个字符串,为其获取 hash 代码,并检查内部 hash 表是否匹配。 If an identical string already exists, a reference to the already existing String object is returned.如果已存在相同的字符串,则返回对已存在的字符串 object 的引用。 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.如果不存在相同的字符串,则制作该字符串的副本,将该副本添加到内部 hash 表中,并返回对该副本的引用。

I guess a description from the documentation is correct.我猜文档中的描述是正确的。 So, only a reference to str is added to the intern pool without copying string object?那么,实习池中只添加了一个对str的引用,而不复制字符串object?

This is easy enough to test directly:这很容易直接测试:

// 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);

Note that result1 is set to true , showing that the original string object is not copied.请注意, result1设置为true ,表明未复制原始string object。 On the other hand, result2 is set to false , showing that the second constructed string object "Hello" was found in the intern pool, and so the string.Intern() method returns that interned instance instead of the newly constructed instance passed in.另一方面, result2设置为false ,表明在实习池中找到了第二个构造的string object "Hello" ,因此string.Intern()方法返回该实习实例而不是传入的新构造实例。

The string.Intern() method does not copy strings. string.Intern()方法不复制字符串。 It just checks whether the reference passed is equal to a string already in the pool, and adds it to the pool if it's not.它只是检查传递的引用是否等于池中已经存在的字符串,如果不是,则将其添加到池中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM