Because performance testing is fun: (using linqpad extension methods)
var val = string.Concat(Enumerable.Range(0, 50).Select(i => i % 10));
foreach(var limit in new[] { 10, 25, 44, 64 })
new Perf<string> {
{ "newstring" + limit, n => new string(val.Take(limit).ToArray()) },
{ "concat" + limit, n => string.Concat(val.Take(limit)) },
{ "truncate" + limit, n => val.Substring(0, Math.Min(val.Length, limit)) },
{ "smart-trunc" + limit, n => val.Length <= limit ? val : val.Substring(0, limit) },
{ "stringbuilder" + limit, n => new StringBuilder(val, 0, Math.Min(val.Length, limit), limit).ToString() },
}.Vs();
The truncate
method was "significantly" faster. #microoptimization
Early
- truncate10 5788 ticks elapsed (0.5788 ms) [in 10K reps, 5.788E-05 ms per]
- smart-trunc10 8206 ticks elapsed (0.8206 ms) [in 10K reps, 8.206E-05 ms per]
- stringbuilder10 10557 ticks elapsed (1.0557 ms) [in 10K reps, 0.00010557 ms per]
- concat10 45495 ticks elapsed (4.5495 ms) [in 10K reps, 0.00045495 ms per]
- newstring10 72535 ticks elapsed (7.2535 ms) [in 10K reps, 0.00072535 ms per]
Late
- truncate44 8835 ticks elapsed (0.8835 ms) [in 10K reps, 8.835E-05 ms per]
- stringbuilder44 13106 ticks elapsed (1.3106 ms) [in 10K reps, 0.00013106 ms per]
- smart-trunc44 14821 ticks elapsed (1.4821 ms) [in 10K reps, 0.00014821 ms per]
- newstring44 144324 ticks elapsed (14.4324 ms) [in 10K reps, 0.00144324 ms per]
- concat44 174610 ticks elapsed (17.461 ms) [in 10K reps, 0.0017461 ms per]
Too Long
- smart-trunc64 6944 ticks elapsed (0.6944 ms) [in 10K reps, 6.944E-05 ms per]
- truncate64 7686 ticks elapsed (0.7686 ms) [in 10K reps, 7.686E-05 ms per]
- stringbuilder64 13314 ticks elapsed (1.3314 ms) [in 10K reps, 0.00013314 ms per]
- newstring64 177481 ticks elapsed (17.7481 ms) [in 10K reps, 0.00177481 ms per]
- concat64 241601 ticks elapsed (24.1601 ms) [in 10K reps, 0.00241601 ms per]
StringBuilder
lets you truncate by shorterning the length, but you still need to perform the length check to avoid widening the string. – Steve Guidi.Trim()
in a manner that makes it misleadingly sound like it mutates the string: "Removes all leading and trailing white-space characters from the current String object." – Mark Amery