实习生字符串误会?字符串、实习生、误会

2023-09-03 01:05:21 作者:寂寞、带点伤

我不明白:

MSDN说:

http://msdn.microsoft.com/en-美国/库/ system.string.intern.aspx

因此​​,文字串与特定值的实例   仅在系统中仅存在一次。

Consequently, an instance of a literal string with a particular value only exists once in the system.

例如,如果您分配相同的文字串到数   变量,运行时检索相同参照字面   字符串从实习生池,并将其分配给每个变量。

For example, if you assign the same literal string to several variables, the runtime retrieves the same reference to the literal string from the intern pool and assigns it to each variable.

请问这种行为是默认的(没有实习)?或使用实习生的方法?

Does this behavior is the Default (without intern ) ? or by using Intern method ?

如果它的默认,所以为什么我会想使用实习生? (实例将是一次了......)? 实习医生神似许光汉走红,回眸瞬间迷一片人,网友纷纷想 生病

If its default , so why will I want to use intern? (the instance will be once already...) ?

如果它不是默认:如果我写1000倍,该行:

If its NOT default : if I write 1000 times this row :

Console.WriteLine(LALALA);

Console.WriteLine("lalala");

1)我会在内存中得到1000次LALALA的? (不使用实习生...)

1 ) will I get 1000 occurrences of "lalala" in memory ? ( without using intern ...)

2)将LALALA最终会Gc'ed?

2) will "lalala" will eventually Gc'ed ?

3)是否LALALA已经被拘留?如果确实如此,为什么将我需要从池中获取它,而不是只写LALALA了吗?

3) Does "lalala" is already interned ? and if it does , why will i need to "get" it from the pool , and not just write "lalala" again ?

我是一个有点混淆。

推荐答案

字符串字面量得到自动(所以,如果你的code包含LALALA1000次,只有一个实例会存在)。实习

String literals get interned automatically (so, if your code contains "lalala" 1000 times, only one instance will exist).

这样的字符串不会得到GC'd和被引用的参考值将成为拘禁之一时。

Such strings will not get GC'd and any time they are referenced the reference will be the interned one.

的String.intern 是有那些字符串的不可以文字 - 比如从用户输入或从文件或数据库,你读知道的会经常重复,因此是值得的实习过程中的生命周期。

string.Intern is there for strings that are not literals - say from user input or read from a file or database and that you know will be repeated very often and as such are worth interning for the lifetime of the process.