Created
November 12, 2022 11:29
-
-
Save nadjibus/a5700410dab368695342105063a27703 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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