字符串实习.NET Framework中 - 有什么好处以及何时使用实习 [英] String interning in .Net Framework - What are the benefits and when to use interning
问题描述
我想知道的过程和字符串的内部实习具体到.NET框架。也想知道用实习和场景/情况下,我们应该使用字符串实习来提高性能的好处。虽然我研究的杰弗里Richter的CLR书实习,但我仍然感到困惑,想知道它的更多细节。
问一个具体问题与样品$ C $如下:C:
私人无效治法()
{
字符串s =字符串; //行1 - 实习文字作为答案解释
//s.intern(); //线2 - 3行中会发生什么,如果我们去掉这一行,会不会有什么区别?
}
私人布尔方法b(字符串compareThis)
{
如果(compareThis ==字符串)// 3号线 - 将这一行使用实习(有和没有取消注释第2行以上)?
{
返回true;
}
返回false;
}
实习是内部实现细节。 不像拳击的,我不认为有任何好处的知道的比你看过的更丰富的书。
微优化实习字符串的好处是手动的最小,因此一般不推荐。
这可能是这样描述的:
类节目
{
常量字符串SomeString =一些字符串; //被拘留
静态无效的主要(字串[] args)
{
尝试
{
VAR S1 = SomeString; //利用实习字符串
VAR S2 = SomeString; //利用实习字符串
VAR S =字符串;
VAR S3 =一些+ S; //没有实习
Console.WriteLine(S1 == S2); //使用实习比较
Console.WriteLine(S1 == S3); //不要使用实习比较
}
赶上(例外五)
{
Console.WriteLine(e.ToString());
}
Console.Read();
}
}
I want to know the process and internals of string interning specific to .Net framework. Would also like to know the benefits of using interning and the scenarios/situations where we should use string interning to improve the performance. Though I have studied interning from the Jeffery Richter's CLR book but I am still confused and would like to know it in more detail.
[Editing] to ask a specific question with a sample code as below:
private void MethodA()
{
string s = "String"; // line 1 - interned literal as explained in the answer
//s.intern(); // line 2 - what would happen in line 3 if we uncomment this line, will it make any difference?
}
private bool MethodB(string compareThis)
{
if (compareThis == "String") // line 3 - will this line use interning (with and without uncommenting line 2 above)?
{
return true;
}
return false;
}
Interning is an internal implementation detail. Unlike boxing, I do not think there is any benefit in knowing more than what you have read in Richer's book.
Micro-optimisation benefits of interning strings manually are minimal hence is generally not recommended.
This probably describes it:
class Program
{
const string SomeString = "Some String"; // gets interned
static void Main(string[] args)
{
try
{
var s1 = SomeString; // use interned string
var s2 = SomeString; // use interned string
var s = "String";
var s3 = "Some " + s; // no interning
Console.WriteLine(s1 == s2); // uses interning comparison
Console.WriteLine(s1 == s3); // do NOT use interning comparison
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.Read();
}
}
这篇关于字符串实习.NET Framework中 - 有什么好处以及何时使用实习的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!