C# – String versus StringBuilder
This is a frequent topic in a lot of interviews I have been a part of recently. A person would have to explain why you should use a StringBuilder instead of a String. If you can’t explain the difference, you probably need to beef up your C# knowledge. You are in luck today. I will show you why.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringvsStringBuilder { class Program { // This is the number of characters to be added static int NUM_OF_CHARACTERS = 25000; static void Main(string[] args) { string data1 = ""; // Remember when we started for the String DateTime data1Start = DateTime.UtcNow; // Add a one to the existing string x times for (int i = 0; i < NUM_OF_CHARACTERS; i++) { data1 += "1"; } // Remember when we ended for the String DateTime data1End = DateTime.UtcNow; StringBuilder data2 = new StringBuilder(); // Remember when we started for the StringBuilder DateTime data2Start = DateTime.UtcNow; // Append a 1 x times to the StringBuilder for (int i = 0; i < NUM_OF_CHARACTERS; i++) { data2.Append("1"); } // Remember when we ended for the StringBuilder DateTime data2End = DateTime.UtcNow; // Creating nice objects for the console output TimeSpan timeSpan1 = new TimeSpan(data1End.Ticks - data1Start.Ticks); TimeSpan timeSpan2 = new TimeSpan(data2End.Ticks - data2Start.Ticks); Console.WriteLine("String appending took {0:N0} milliseconds", timeSpan1.TotalMilliseconds); Console.WriteLine("StringBuilder appending took {0:N0} milliseconds", timeSpan2.TotalMilliseconds); // Check to see if the string and the toString of the StringBuilder are equal if(data1.Equals(data2.ToString())) { Console.WriteLine("Yes, the two strings are equal."); } Console.ReadKey(); } } } |
The results on my system were:
String appending took 706 milliseconds
StringBuilder appending took 1 milliseconds
Yes, the two strings are equal.
Why should you use StringBuilder instead of String? If you are appending a lot of strings, StringBuilder is more efficient.
Eliot 12:15 pm on January 26, 2011 Permalink |
Thanks for stopping by and I am glad you found this helpful.