今天飛書羣裏同事爭論 枚舉.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;
}