Skip to content

Instantly share code, notes, and snippets.

@nadjibus
Created November 12, 2022 11:29
Show Gist options
  • Save nadjibus/a5700410dab368695342105063a27703 to your computer and use it in GitHub Desktop.
Save nadjibus/a5700410dab368695342105063a27703 to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Reflection;
public class Program
{
public static void Main(string[] args)
{
BenchmarkRunner.Run(typeof(Program).Assembly);
}
public class SetValueBenchmark
{
private static readonly TestClass TestClass = new TestClass { StringProperty = "Initial Value", IntProperty = 1, ObjectProperty = new TestClass() };
private static readonly PropertyInfo StringPropertyInfo = typeof(TestClass).GetProperty(nameof(TestClass.StringProperty));
private static readonly PropertyInfo IntPropertyInfo = typeof(TestClass).GetProperty(nameof(TestClass.IntProperty));
private static readonly PropertyInfo ObjectPropertyInfo = typeof(TestClass).GetProperty(nameof(TestClass.ObjectProperty));
[Benchmark]
public void DirectSet()
{
TestClass.StringProperty = "Test String";
TestClass.IntProperty = 1984;
TestClass.ObjectProperty = new TestClass();
}
[Benchmark]
public void ReflectionSet()
{
StringPropertyInfo.SetValue(TestClass, "Test String 2");
IntPropertyInfo.SetValue(TestClass, 4891);
ObjectPropertyInfo.SetValue(TestClass, new TestClass());
}
}
}
public class TestClass
{
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public TestClass ObjectProperty { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment