创建控制台项目(或修改现有项目的Main方法代码),Nget导入Benchmark0.13.12,创建测试类:
public class StringBenchMark
{
int[] numbers;
public StringBenchMark() {
numbers = Enumerable.Range(1, 20000).ToArray();
}
[Benchmark(Baseline = true, OperationsPerInvoke = 10)] //OperationsPerInvoke设置太小无法充分测试出性能差异,设置太大耗时较长
public string StringConcatenationTesk()
{
string s = string.Empty;
for(var i = 0; i < numbers.Length; i++)
{
s += numbers[i].ToString() + ",";
}
return s;
}
[Benchmark(OperationsPerInvoke = 10)]
public string StringBuilderTest() {
var builder = new StringBuilder();
for(var i =0; i < numbers.Length; ++i)
{
builder.Append(numbers[i].ToString());
builder.Append(",");
}
return builder.ToString();
}
}
static void Main(string[] args)
{
BenchmarkRunner.Run<StringBenchMark>();
Console.ReadLine();
}
右键项目--属性, 勾选优化编译。
运行后得到如下内容:
注:关注StdDev(标准偏差)即可,越小越好。 Mean为平均值,ERROR为标准误差;Ratio为异众比率;