Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.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# 什么';是什么导致了字符串连接时间的激增?_C#_Performance_String Concatenation_Stopwatch - Fatal编程技术网

C# 什么';是什么导致了字符串连接时间的激增?

C# 什么';是什么导致了字符串连接时间的激增?,c#,performance,string-concatenation,stopwatch,C#,Performance,String Concatenation,Stopwatch,因此,出于好奇和无聊,我在做基准测试。我从一个空白字符串开始,创建了1000个空白中的另一个,并开始使用普通的低效字符串连接将一个添加到另一个,计时每次所用的时间 string s1 = ""; string s2 = ""; while (s2.Length < 1000) { s2 += " "; } while (true) { Stopwatch sw = Stopwatch.StartNew(); s1 += s2; sw.Stop();

因此,出于好奇和无聊,我在做基准测试。我从一个空白字符串开始,创建了1000个空白中的另一个,并开始使用普通的低效字符串连接将一个添加到另一个,计时每次所用的时间

string s1 = "";
string s2 = "";
while (s2.Length < 1000)
{
    s2 += " ";
}

while (true)
{
    Stopwatch sw = Stopwatch.StartNew();
    s1 += s2;
    sw.Stop();

    Console.WriteLine(" {0}| {1}", s1.Length, sw.ElapsedMilliseconds);
}
这些示例来自字符串开始显著变大时,但模式从一开始就保持不变。大体上,前一千个左右的样本太小,无法注意到图案,但在1.8k标记附近,它是可识别的

我的第一个假设是,在幕后,这些角色被存储在某种ArrayList/vector类型的交易中,一旦满了,其大小会翻倍,但当我进一步思考时,这并不合适——如果是这样的话,尖峰将以指数周期而不是线性周期出现


简言之,这到底是怎么回事?

创建字符串并丢弃它们会产生垃圾。一旦使用了一定量的内存,就会发生垃圾收集并暂停进程。因为在您的过程中没有其他事情发生,而且您总是使字符串具有相同的长度,所以GC总是在同一时间发生(每运行6次)


为避免对计时造成影响,请在每次运行时启动计时器之前调用。

可能是垃圾收集。如果你真的感兴趣,试着运行一个分析器;恐怕我们只能猜测。GC是否足够一致,可以精确地每六次迭代发生一次(假设整个数据集都是一致的)?
 Length     | Time (ms)
 -----------------------
 32250000   | 117
 32251000   | 44
 32252000   | 31
 32253000   | 30
 32254000   | 30
 32255000   | 32
 32256000   | 129
 32257000   | 35
 32258000   | 43
 32259000   | 34
 32260000   | 30
 32261000   | 29
 32262000   | 107
 32263000   | 47
 32264000   | 29
 32265000   | 30
 32266000   | 31
 32267000   | 29
 32268000   | 110
 32269000   | 46
 32270000   | 31
 32271000   | 30
 32272000   | 30
 32273000   | 30
 32274000   | 113