.NET字符串性能问题

Abe*_*ler 3 .net c# string performance

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

例1:

StringBuilder letsCount = new StringBuilder("Let's count! ");
string sep = ", ";
for(int i=; i< 100; i++)
{
     letsCount.Append(i + sep);
}
Run Code Online (Sandbox Code Playgroud)

例2:

StringBuilder letsCount = new StringBuilder("Let's count! ");
for(int i=; i< 100; i++)
{
     letsCount.Append(i + ", ");
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 12

.NET CLR比这更聪明.它" 实习 "字符串文字,因此只有一个实例.

值得注意的是,如果您真的担心字符串连接,您可能希望将单个Append调用转换为两个追加调用.但实际情况是,两次呼叫的开销可能超过任何次要的连接成本.无论哪种情况,除非在非常严格的条件下,它几乎无法估量.