Archive for the ‘C#’ Category
String vs. StringBuilder. January 7th, 2009
Do you prefer…
1 2 3 4 | for (_i=0;_i<_max;_i++) { mString += ", Another String"; } |
rather than…
1 2 3 4 | for (_i=0;_i<_max;_i++) { mStringBuilder.Append(", Another String"); } |
I hope you don’t.
Here is why. The String type is an immutable object type which means that it will create a new string every time it is modified. This will make you pay with your application’s performance when you do long string concatenations. In other hand the StringBuilder is a mutable object type, so it will not create a new StringBuilder every time you modify it. The StringBuilder will create a new buffer only if it reaches its limit if not it will just append the existing one.
I wrote this proof-of-concept application in order to provide you with some performance metrics.
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 | using System; namespace testStringBuilder { class Program { public static void Main(string[] args) { int _max = 10000; int _i = 0; double mStringLapse = 0; double mStringBuilderLapse = 0; DateTime mStartTime; TimeSpan mLapse; string mString; System.Text.StringBuilder mStringBuilder; while (_max < 1000000) { mString = ""; mStringBuilder = new System.Text.StringBuilder(""); mStartTime = DateTime.Now; for (_i=0;_i<_max;_i++) { mString += ", Another String"; } mLapse = DateTime.Now.Subtract(mStartTime); mStringLapse = mLapse.TotalMilliseconds; mStartTime = DateTime.Now; for (_i=0;_i<_max;_i++) { mStringBuilder.Append(", Another String"); } mLapse = DateTime.Now.Subtract(mStartTime); mStringBuilderLapse = mLapse.TotalMilliseconds; _max +=_max; Console.WriteLine(_i.ToString() + " Concatenations | String=" + mStringLapse.ToString() + "ms StringBuilder=" + mStringBuilderLapse.ToString() + "ms"); } Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } } |
I guess the results are self explanatory.
1 | int _max = 10000; |

1 | int _max = 10; |
