如何进一步优化此代码?

Sha*_* Le 1 c# optimization

看下面的代码:

StringBuilder row = TemplateManager.GetRow("xyz"); // no control over this method 
StringBuilder rows = new StringBuilder();

foreach(Record r in records)
{
    StringBuilder thisRow = new StringBuilder(row.ToString());
    thisRow.Replace("%firstName%", r.FirstName)
       .Replace("%lastName%", r.LastName)
          // all other replacement goes here
       .Replace("%LastModifiedDate%", r.LastModifiedDate);

    //finally append row to rows
    rows.Append(thisRow);
}
Run Code Online (Sandbox Code Playgroud)

目前有3个StringBuilders和row.ToString()在循环内.这里有进一步优化的空间吗?

Ben*_*n S 12

这是您申请中的瓶颈吗?你有没有对它进行分析并知道它需要优化?

除非您需要,否则不要进行优化.预先成熟的优化导致可维护的代码更少,甚至可能优化甚至不优化.

  • 当然,这不能回答这个问题. (3认同)

Igb*_*man 8

我认为thisRow用字符串替换可能会更快,但我做了一些测试并且StringBuilder赢了.

String.Replace()创建一个新的字符串,这是昂贵的.StringBuilder.Replace()修改其缓冲区中的字符串,这样便宜.在我的测试中,我使用了一串500个字符并执行了6个字符Replace().StringBuilder的速度提高了约5%,包括每次迭代都创建一个新的.

但是,你应该做的一件事是移动row.ToString()循环外部.为每条记录调用它是通过创建一个新字符串来浪费周期.

String row = TemplateManager.GetRow("xyz").ToString();
StringBuilder rows = new StringBuilder(); 

foreach(Record r in records) 
{ 
    StringBuilder thisRow = new StringBuilder(row);  
    thisRow.Replace("%firstName%", r.FirstName) 
                   .Replace("%lastName%", r.LastName) 
                   .Replace("%LastModifiedDate%", r.LastModifiedDate); 
    rows.Append(thisRow);
}    
Run Code Online (Sandbox Code Playgroud)


Car*_*ter 5

你可以row.ToString()走出循环; row永远不会改变循环内部.