Look at the following code:
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);
}
Currently 3 StringBuilders and row.ToString() is inside a loop. Is there any room for further optimization here?
I thought it might be quicker to replace
thisRowwith a string, but I did some tests and StringBuilder won.String.Replace()creates a new string, which is expensive.StringBuilder.Replace()modifies the string in its buffer, which is less expensive. In my test I used a string of 500 chars and performed 6Replace()‘s. StringBuilder was about 5% faster, including creating a new one each iteration.However, one thing you should do is move the
row.ToString()outside the loop. Calling it for each record is wasting cycles by creating a new string.