It is believed that StringBuilder should be used if you have a concatenation of large strings and / or all of this happens in a loop with a large number of iterations. This is due to the fact that the lines are immutable, and therefore each time the line is changed, a new one is actually created. At the same time, StringBuilder deprived of this disadvantage. Here you have a small test, which, however, does not claim to be comprehensively accurate. We have four methods:
private static long Plus(int counts) { string res = ""; var watch = Stopwatch.StartNew(); for (var i = 0; i < counts; i++) { res = res + DateTime.Now.ToString(); } return watch.ElapsedMilliseconds; } private static long Concat(int counts) { string res = ""; var watch = Stopwatch.StartNew(); for (var i = 0; i < counts; i++) { res = String.Concat(res, DateTime.Now.ToString()); } return watch.ElapsedMilliseconds; } private static long Format(int counts) { string res = ""; var watch = Stopwatch.StartNew(); for (var i = 0; i < counts; i++) { res = String.Format("{0}{1}", res, DateTime.Now.ToString()); } return watch.ElapsedMilliseconds; } private static long Build(int counts) { StringBuilder res = new StringBuilder(); var watch = Stopwatch.StartNew(); for (var i = 0; i < counts; i++) { res = res.Append(DateTime.Now.ToString()); } string res2 = res.ToString(); return watch.ElapsedMilliseconds; }
The first is for the "normal" addition of strings, the second for String.Concat , the third for String.Format, the fourth for StringBuilder.Append . We run them through a different number of iterations. We get this:
Plus(1000) - время выполнения 7 мс Concat(1000) - время выполнения 3 мс Format(1000) - время выполнения 8 мс Build(1000) - время выполнения < 1 мс Plus(2000) - время выполнения 13 мс Concat(2000) - время выполнения 11 мс Format(2000) - время выполнения 20 мс Build(2000) - время выполнения 1 мс Plus(5000) - время выполнения 66 мс Concat(5000) - время выполнения 56 мс Format(5000) - время выполнения 133 мс Build(5000) - время выполнения 2 мс Plus(10000) - время выполнения 266 мс Concat(10000) - время выполнения 248 мс Format(10000) - время выполнения 591 мс Build(10000) - время выполнения 5 мс Plus(20000) - время выполнения 1663 мс Concat(20000) - время выполнения 1624 мс Format(20000) - время выполнения 3925 мс Build(20000) - время выполнения 10 мс
Draw your own conclusions
UPD on a few applications of workers added a method for String.Format. God knows that, but to complete the picture will come down.
+faster. Another clarification question: is it literal strings that add up? or variables? - Grundy+this is the same Concat - Grundy