Skip to content

Instantly share code, notes, and snippets.

@overing
Created November 30, 2023 01:44
Show Gist options
  • Save overing/c6c9530021ba440a3faf1d198df9d86c to your computer and use it in GitHub Desktop.
Save overing/c6c9530021ba440a3faf1d198df9d86c to your computer and use it in GitHub Desktop.
#define 有提供存取成員的公開屬性
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using BenchmarkDotNet.Attributes;
using TestDatas;
/*
// * Summary *
BenchmarkDotNet=v0.13.5, OS=Windows 11 (10.0.22621.2715/22H2/2022Update/SunValley2)
12th Gen Intel Core i5-12400, 1 CPU, 12 logical and 6 physical cores
.NET SDK=8.0.100
[Host] : .NET 6.0.21 (6.0.2123.36311), X64 RyuJIT AVX2
DefaultJob : .NET 6.0.21 (6.0.2123.36311), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev | Ratio | Rank | Gen0 | Allocated | Alloc Ratio |
|----------------------- |-----------:|----------:|----------:|------:|-----:|-------:|----------:|------------:|
| WithPublicProperty | 0.0301 ns | 0.0126 ns | 0.0111 ns | 0.001 | 1 | - | - | 0.00 |
| WithExpressionCompiled | 0.6044 ns | 0.0059 ns | 0.0055 ns | 0.025 | 2 | - | - | 0.00 |
| WithReflection | 24.2024 ns | 0.4174 ns | 0.3904 ns | 1.000 | 3 | 0.0025 | 24 B | 1.00 |
*/
namespace Benchmarks
{
[MemoryDiagnoser]
[RankColumn]
public class TestExpression
{
MyData _data;
FieldInfo _fieldInfo;
Func<MyData, int> _delegate;
[GlobalSetup]
public void Setup()
{
_data = new MyData(16);
_fieldInfo = typeof(MyData).GetField("_value", BindingFlags.Instance | BindingFlags.NonPublic);
var parameter = Expression.Parameter(typeof(MyData));
var member = Expression.PropertyOrField(parameter, "_value");
var lambda = Expression.Lambda<Func<MyData, int>>(member, parameter);
_delegate = lambda.Compile();
}
#if 有提供存取成員的公開屬性
[Benchmark]
public int WithPublicProperty() => _data.Value;
#endif
[Benchmark]
public int WithExpressionCompiled() => _delegate(_data);
[Benchmark(Baseline = true)]
public int WithReflection() => (int)_fieldInfo.GetValue(_data);
}
}
namespace TestDatas
{
public sealed class MyData
{
private int _value;
public MyData(int value) => _value = value;
#if 有提供存取成員的公開屬性
public int Value
{
get => _value;
set => _value = value;
}
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment