Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .NET字符串性能问题_C#_.net_Performance_String - Fatal编程技术网

C# .NET字符串性能问题

C# .NET字符串性能问题,c#,.net,performance,string,C#,.net,Performance,String,从性能的角度来看,使用“Example1”是否更好?我假设“Example2”会在每次迭代中在堆上创建一个新字符串,而“Example1”不会 例1: StringBuilder letsCount = new StringBuilder("Let's count! "); string sep = ", "; for(int i=; i< 100; i++) { letsCount.Append(i + sep); } StringBuilder-letscont=new-S

从性能的角度来看,使用“Example1”是否更好?我假设“Example2”会在每次迭代中在堆上创建一个新字符串,而“Example1”不会

例1:

StringBuilder letsCount = new StringBuilder("Let's count! ");
string sep = ", ";
for(int i=; i< 100; i++)
{
     letsCount.Append(i + sep);
}
StringBuilder-letscont=new-StringBuilder(“让我们数一数!”);
字符串sep=“,”;
for(int i=;i<100;i++)
{
Letscont.Append(i+sep);
}
例2:

StringBuilder letsCount = new StringBuilder("Let's count! ");
for(int i=; i< 100; i++)
{
     letsCount.Append(i + ", ");
}
StringBuilder-letscont=new-StringBuilder(“让我们数一数!”);
for(int i=;i<100;i++)
{
附加(i+“,”);
}

NET CLR比这聪明得多。它使用“”字符串文本,因此只有一个实例


还值得注意的是,如果您真正关心字符串连接,您可能希望将单个追加调用转换为两个追加调用。然而,现实情况是,两个调用的开销可能超过任何较小的连接成本。在这两种情况下,除了在非常受控的条件下,它几乎是不可测量的。

它们是相同的。

实际上,一种更快的方法是

string letsCount = "Let's count! ";
string[] numbers = new string[100];
for(int i=0; i< 100; i++)
{ 
   numbers[i]=i+", ";
}
String.Join(letsCount, numbers);
string letscont=“让我们数一数!”;
字符串[]数字=新字符串[100];
对于(int i=0;i<100;i++)
{ 
数字[i]=i+“,”;
}
连接(letsCount、数字);

我认为您应该尝试一下,使用秒表,这是非常好的测量方法,使用stringbuilder在超过4-5次连接时已经更快了。我非常清楚使用stringbuilder进行多次连接的好处。我指的是附加(I+sep)和附加(I)之间的差异;附加(sep);我确实采纳了你的建议,并计时了。x100-0ms(72个滴答声)vs 0ms(61个滴答声),x100000-32ms(71517个滴答声)vs 26ms(58870个滴答声)+1这个有趣的分析让我想知道(显然)将循环索引变量从int自动转换为“whatever”的“内部成本”(因此它可以与SB连接)。对我来说,这也提出了一个有趣的问题:在什么情况下(如果有的话),“s1.Append(i).Append(s2);”这样的“链式”附录会有“回报”。谢谢,+1让我接触到了我从未见过的StringBuilder的用法。。。自动将内部非字符串参数转换为字符串(如果这是正确的描述方式)。。。(这在MSDN中没有记录)。非常有趣,谢谢链接。我将来必须记住这一点。在有100个串接的字符串之后,我很想看到这个图。。。