-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Closed
Labels
Milestone
Description
Description
While trying to select a fastest method to retrieve custom attributes I've came across very peculiar result. I've setup 3 tests to benchmark available methods:
private PropertyInfo property = typeof(Access1).GetTypeInfo().GetProperty(nameof(Property));
[Import]
public int Property { get; set; }
[Benchmark]
public object GetCustomAttributesAll()
{
return property.GetCustomAttributes(true);
}
[Benchmark]
public object GetCustomAttribute()
{
return property.GetCustomAttribute(typeof(ImportAttribute), true);
}
[Benchmark]
public object GetCustomAttributesType()
{
return property.GetCustomAttributes(typeof(ImportAttribute), true);
}A simple property with just one attribute.
Logically, PropertyInfo.GetCustomAttribute(typeof(ImportAttribute), true); should be the fastest. No array allocation is necessary to return the attribute, but to my surprise it is not the case. It is 4 (four) times slower than the other two methods!
BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.1198 (1909/November2018Update/19H2)
AMD Ryzen Threadripper 2970WX, 1 CPU, 48 logical and 24 physical cores
.NET Core SDK=5.0.100
[Host] : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT
Job-OETPQV : .NET Core 5.0.0 (CoreCLR 5.0.20.51904, CoreFX 5.0.20.51904), X64 RyuJIT
IterationCount=3 LaunchCount=1 WarmupCount=3
| Method | Mean | Error | StdDev |
|------------------------ |-----------:|----------:|---------:|
| GetCustomAttributesAll | 742.1 ns | 83.02 ns | 4.55 ns |
| GetCustomAttribute | 3,724.1 ns | 201.08 ns | 11.02 ns |
| GetCustomAttributesType | 775.8 ns | 10.39 ns | 0.57 ns |
This timing does not make any sense and should be looked at.