测试用例--除去末尾特定字符或字符串,Remove方法和TrimEnd方法的比较
结论:
如果是除去末尾特定字符或字符串:TrimEnd方法性能优于Remove方法
具体测试用例如下:
Stopwatch watcher = new Stopwatch();
watcher.Reset();
watcher.Start();
int count = 1000000;
List<string> strList = new List<string>();
for (int i = 0; i < count; i++)
{
strList.Add(i.ToString());
}
#region 测试用例--除去末尾特定字符或字符串,Remove方法和TrimEnd方法的比较
string result;
#region Remove方法
watcher.Reset();
watcher.Start();
StringBuilder builder = new StringBuilder();
foreach (string item in strList)
{
builder.Append(item);
builder.Append(',');
}
result = builder.Remove(builder.Length - 1, 1).ToString();
Console.WriteLine("StringBuilder.Remove:{0}", watcher.ElapsedMilliseconds);
#endregion
#region TrimEnd方法
watcher.Reset();
watcher.Start();
result = builder.ToString().TrimEnd(',');
Console.WriteLine("StringBuilder.TrimEnd:{0}", watcher.ElapsedMilliseconds);
#endregion
/*************************************************
* 测试用例:除去末尾特定字符或字符串,Remove方法和TrimEnd方法的比较
* 结论:如果是除去末尾特定字符或字符串:TrimEnd方法性能优于Remove方法
* 测试结果如下:(时间为毫秒)
* --------------------------------------
* 数据: | 10W | 100W | 1000W
* --------------------------------------
* Remove | 7 | 81 | 786
* ---------------------------------------
* TrimEnd | 0 | 12 | 108
*
*/
#endregion