How come for loops in C# are so slow when concatenating strings? [duplicate]

  • A+
Category:Languages

This question already has an answer here:

I wrote a program that runs a simple for loop in both C++ and C#, yet the same thing takes dramatically longer in C#, why is that? Did I fail to account for something in my test?

C# (13.95s)

static double timeStamp() {     return (double)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; }  static void Main(string[] args) {     double timeStart = timeStamp();      string f = "";     for(int i=0; i<100000; i++) {         f += "Sample";     }      double timeEnd = timeStamp();     double timeDelta = timeEnd - timeStart;     Console.WriteLine(timeDelta.ToString());     Console.Read(); } 

C++ (0.20s)

long int timeStampMS() {     milliseconds ms = duration_cast<milliseconds> (system_clock::now().time_since_epoch());     return ms.count(); }  int main() {     long int timeBegin = timeStampMS();      string test = "";      for (int i = 0; i < 100000; i++) {         test += "Sample";     }       long int timeEnd = timeStampMS();     long double delta = timeEnd - timeBegin;      cout << to_string(delta) << endl;     cin.get(); } 


On my PC, changing the code to use StringBuilder and converting to a String at the end, the execution time went from 26.15 seconds to 0.0012 seconds, or over 20,000 times faster.

var fb = new StringBuilder(); for (int i = 0; i < 100000; ++i) {     fb.Append("Sample"); } var f = fb.ToString(); 

As explained in the .Net documentation, the StringBuilder class is a mutable string object that is useful for when you are making many changes to a string, as opposed to the String class, which is an immutable object that requires a new object creation every time you e.g. concatenate two Strings together. Because the implementation of StringBuilder is a linked list of character arrays, and new blocks are added up to 8000 characters at a time, StringBuilder.Append is much faster.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: