CSharp · Console
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
public class BaseClass
{
public int MyProperty { get; set; }
public int a { get; set; }
}
public class DerivedClass : BaseClass
{
public new string MyProperty { get; set; }
public int b { get; set; }
}
class Program
{
static void Main()
{
Type type = typeof(DerivedClass);
string path = "MyProperty";
int iterations = 100000;
// Benchmark first code snippet
Stopwatch stopwatch1 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
PropertyInfo[] infos = type.GetProperties();
PropertyInfo info = infos.FirstOrDefault(p => p.Name.Equals(path, StringComparison.OrdinalIgnoreCase));
}
stopwatch1.Stop();
Console.WriteLine($"First code snippet time: {stopwatch1.ElapsedMilliseconds} ms");
// Benchmark second code snippet
Stopwatch stopwatch2 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
PropertyInfo info = null;
try
{
info = type.GetProperty(path);
}
catch (AmbiguousMatchException)
{
info = type.GetProperty(path, BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
}
}
stopwatch2.Stop();
Console.WriteLine($"Second code snippet time: {stopwatch2.ElapsedMilliseconds} ms");
}
}