在(据说)高性能code用GetCurrentMethod高性能、code、GetCurrentMethod

2023-09-03 05:03:39 作者:宝贝

有关采伐的目的,在我们的应用程序的一些方法包括以下行:

 昏暗的日志作为的ILog = GetLog(Reflection.MethodBase.GetCurrentMethod()。DeclaringType)
 

我有什么可以被描述为一种非理性的恐惧的反思,我尽量保持在检查。然而,呼吁像这样在潜在地执行了一百次,第二个问题我的方法。我不知道像我应约反映;但在简单的文件看,它看起来对我来说,我可以替换为以下:

 昏暗的日志作为的ILog = GetLog(Me.GetType())
 
一个测试 WebService 和数据库连接的高性能工具 DBTest

我的问题有三个方面:

确实 Me.GetType()实际返回相同的键入 GetCurrentMethod() .DeclaringType ? 确实 Me.GetType()其实做任何事情的不同的的距离 GetCurrentMethod()。DeclaringType ,或者是做同样的事情在引擎盖下? 我应该甚至不担心这个呢?性能是这个应用的关键;该程序的运行的罚款,但我们的企业的性质就是这样,如果我们能够在这里和那里刮掉甚至几微秒,这是非常有用的。 解决方案

在你的情况 this.GetType()将产生相同的结果为 MethodBase.GetCurrentMethod()。DeclaringType 一样。见JaredPar的答案的情况下这两个调用将返回不同的类型。

在一般情况下暴露的部件(通过 MemberInfo.ReflectedType 属性获得)和声明一个部件(经由获得的类型的类型的 MemberInfo.DeclaringType 属性)可能会有所不同。

更新

我只是异形它使用C# - this.GetType()要求 2.5纳秒每次通话,而 MethodBase.GetCurrentMethod()DeclaringType 要求 2490 NS 每次通话 - 让您拥有约因子加快 1200

[英特尔酷睿2 6400 2.13 GHz的| 3.5吉布|的WinXP专业版SP2 | .NET FX 3.5 SP1 |发布|如果没有调试器]

For logging purposes, some methods in our application include the following line:

Dim Log As ILog = GetLog(Reflection.MethodBase.GetCurrentMethod().DeclaringType)

I have what might be described as an irrational fear of reflection, which I try to keep in check. However, calls like this in methods that are executed potentially a hundred times a second concern me. I don't know as much as I should about reflection; but from looking briefly over the documentation, it looks to me like I could replace the following with:

Dim Log As ILog = GetLog(Me.GetType())

My question is three-fold:

Does Me.GetType() actually return the same Type as GetCurrentMethod().DeclaringType? Does Me.GetType() actually do anything differently from GetCurrentMethod().DeclaringType, or is it doing the same thing under the hood? Should I not even be worried about this at all? Performance is critical in this application; the program runs fine, but the nature of our business is such that if we can shave off even a few microseconds here and there, that is useful.

解决方案

In your situation this.GetType() will yield the same result as MethodBase.GetCurrentMethod().DeclaringType does. See JaredPar's answer for a situation where both calls will return different types.

In the general case the type exposing a member (obtained via the MemberInfo.ReflectedType property) and the type declaring a member (obtained via the MemberInfo.DeclaringType property) may differ.

UPDATE

I just profiled it using C# - this.GetType() required 2.5 ns per call while MethodBase.GetCurrentMethod().DeclaringType required 2490 ns per call - so you have a speed up of about factor 1200.

[Intel Core 2 6400 2.13 GHz | 3.5 GiB | WinXP Pro SP2 | .NET FX 3.5 SP1 | Release | Without Debugger]