A small example of C using StringBuilder to improve string concatenation performance

  • 2020-05-17 06:16:26
  • OfStack

After monitoring 1 with Stopwatch, it was found that the most time-consuming function was SaveToExcel

This function iterates through all the data rows, generates the Excel rows through the Replace substitution tag, and then accumulates the row data and assigns it to a string


string excelString = ""; 
foreach(var item in list){ 
        excelString += string.Format("<row>....{0}</row>",list.Title); 
} 

See this... Immediately remembered the countless martyrs of the warning, string concatenation memory operation principle and so on. So the big hand 1 wave, the code is completely deleted, changed to the following form

string excelString = new StringBuilder(); 
foreach(var item in list){ 
      excelString.AppendFormat("<row>......{0}</row>",list.Title); 
} 

Again, the efficiency was improved several times immediately. You used to need 30s for 8000 lines, now you only need 2s


Related articles: