Advantage of using CustomAttributes vs GetCustomAttributes()

我与影子孤独终老i 提交于 2019-12-05 07:13:42

You are making a traditional benchmarking mistake, one that makes many .NET programmers think that Reflection is slow. Slower than it actually is. Reflection is very lazy, you don't pay for it when you don't use it. Which makes your first measurement include all the cost of page-faulting the metadata into RAM and setup the type info reflection cache. That cost is not included in the second measurement, making GetCustomAttributes() look better than it actually is.

Always include a loop around the benchmark code, run it 10 times. You'll now see that the CustomAttributes property isn't actually that slow, I measure it at (roughly) 0.083 vs 0.063 seconds, ~30% slower.

The CustomAttributes property needed to be added in .NET 4.5 to support the language projection for WinRT. You cannot use GetCustomAttributes() in a Store, Phone or PCL project. Reflection is very different in WinRT, an inevitable side-effect of it being a COM based api. Implementation code is enough to make anyone's eyes bleed but the broad outline is that the property is implemented in C# and the method is implemented in the CLR. The C# code needs to do more work to handle the language projection details so is inevitably slower.

So just keep using GetCustomAttributes(), use the property when you have to. A 30% speed difference isn't otherwise a drastic reason to compromise style and readability, apply your common sense.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!