基准测试BenchmarkDotNet
今天飞书群里同事争论 枚举.GetHashCode()会装箱,要改为(int)枚举,争吵不下
纸上谈兵无法说服另外的人,上BenchmarkDotNet基准测试
添加BenchmarkDotNet库
<PackageReference Include="BenchmarkDotNet" Version="0.13.5" />
性能测试用例
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<EnumParseBenchmark>();
Console.ReadLine();
}
}
/// <summary>
/// (int)枚举 与 枚举.GetHashCode() 性能对比
/// </summary>
public class EnumParseBenchmark
{
enum color
{
none = 1,
Red = 2,
yellow = 3,
green = 4,
black = 5,
}
[Benchmark]
public int enumGetHashCode() => color.Red.GetHashCode();
[Benchmark]
public int enumIntParse() => (int)color.Red;
}