因为性能测试很有趣:(使用linqpad扩展方法)
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();
截断法“明显”更快。# microoptimization
早期
truncate10 5788滴答流逝(0.5788 ms) [10K次,5.788E-05 ms /次]
smart-trunc10 8206滴答流逝(0.8206 ms) [10K次,8.206E-05 ms /次]
stringbuilder10 10557滴答流逝(1.0557 ms) [10K次,0.00010557 ms /次]
concat10 45495滴答流逝(4.5495 ms) [10K次,0.00045495 ms /次]
时间流逝(7.2535 ms) [10K次,0.00072535 ms /次]
Late
truncate44 8835滴答流逝(0.8835 ms) [10K次,8.835E-05 ms /次]
13106滴答流逝(1.3106 ms) [10K次,0.00013106 ms /次]
smart-trunc44 14821滴答流逝(1.4821毫秒)[10K次,0.00014821毫秒/次]
时间流逝(14.4324 ms) [10K次,0.00144324 ms /次]
concat44 174610滴答流逝(17.461毫秒)[每10K次,0.0017461毫秒]
太长时间
smart-trunc64 6944滴答流逝(0.6944毫秒)[在10K次中,6.944E-05毫秒每]
truncate64 7686滴答流逝(0.7686 ms) [10K次,7.686E-05 ms /次]
stringbuilder64 13314滴答流逝(1.3314 ms) [10K次,0.00013314 ms /次]
时间流逝(17.7481 ms) [10K次,0.00177481 ms /次]
concat64 241601滴答流逝(24.1601毫秒)[每10K次,0.00241601毫秒]