相关疑难解决方法(0)

Object.GetType()的性能

我们的应用程序中有很多日志记录调用.我们的记录器采用System.Type参数,因此它可以显示创建调用的组件.有时候,当我们受到打扰时,我们会做以下事情:

class Foo
{
  private static readonly Type myType = typeof(Foo);

  void SomeMethod()
  {
     Logger.Log(myType, "SomeMethod started...");
  }
 }
Run Code Online (Sandbox Code Playgroud)

因为这只需要获取Type对象一次.但是,我们没有任何实际指标.任何人都知道这节省了多少调用this.GetType()每次我们登录?

(我意识到我可以自己完成指标并没有什么大问题,但是嘿,什么是StackOverflow?)

.net c# performance

45
推荐指数
4
解决办法
3万
查看次数

C#的类型操作符的效率(或者它在MSIL中的表示形式)

我知道过早的优化是所有邪恶的母亲.但是,我正在定义一个泛型方法,它使用Reflection来检索其泛型类型的元数据,并想知道是否typeof(T)多次调用,如下面的代码片段所示:

private static Dictionary<Type, PropertyInfo[]> elementProperties;

private static T MakeElement<T>(SqlDataReader reader) where T : class, new() {
    PropertyInfo[] properties;
    if (elementProperties.ContainsKey(typeof(T)))
        properties = elementProperties[typeof(T)];
    else
        properties = elementProperties[typeof(T)] = typeof(T).GetProperties();

    // more code...
}
Run Code Online (Sandbox Code Playgroud)

...比将类型对象存储到变量中的效率低,如下面的代码片段所示:

private static Dictionary<Type, PropertyInfo[]> elementProperties;

private static T MakeElement<T>(SqlDataReader reader) where T : class, new() {
    PropertyInfo[] properties;
    Type type = typeof(T);
    if (elementProperties.ContainsKey(type))
        properties = elementProperties[type];
    else
        properties = elementProperties[type] = type.GetProperties();

    // more code...
}
Run Code Online (Sandbox Code Playgroud)

...?

如果我正确理解编译器理论(我认为我这样做),这个问题可以简化为以下问题:

当JIT编译器实例化泛型类型时,它是否替换了[无论MSIL表示typeof(T)形式]的每个实例...

  1. ...对实际类型对象的引用?(好) …

c#

16
推荐指数
2
解决办法
3908
查看次数

标签 统计

c# ×2

.net ×1

performance ×1