c# - 为什么在 .NET 中转换比反射快?

标签 c# .net reflection casting

我有一个事件处理程序,它需要确定类型并在匹配特定类型时执行代码。最初我们将它转​​换为一个对象,如果它不为空,我们就执行代码,为了加快速度,我使用了反射,但它实际上减慢了它的速度,我不明白为什么。

这是一个代码示例

Trace.Write("Starting using Reflection");
if (e.Item.GetType() == typeof(GridDataItem))
{
      bool isWatch = Convert.ToBoolean(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IsWatch"]);
      if (isWatch)
      {
          e.Item.Style["Font-Weight"] = "bold";
      }
 }
 Trace.Write("Ending using Reflection");
 Trace.Write("Starting using Cast");
 GridDataItem gridItem = e.Item as GridDataItem;
 if (gridItem !=null)
 {
     bool isWatch = Convert.ToBoolean(gridItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IsWatch"]);
     if (isWatch)
     {
         gridItem.Style["Font-Weight"] = "bold";
     }
  }
  Trace.Write("Ending using Cast"); 

这是我得到的跟踪输出

Starting using Reflection  0.79137944962406 0.576538
Ending using Reflection    0.791600842105263    0.000221
Starting using Cast    0.791623353383459    0.000023
Ending using Cast      0.791649308270677    0.000026
Starting using Reflection  0.876253801503759    0.084604
Ending using Reflection    0.87631790075188 0.000064
Starting using Cast    0.87633445112782 0.000017
Ending using Cast      0.87634950075188 0.000015

这不是很多,但如果我们不得不随着时间的推移经常这样做,它可能会加起来。

最佳答案

反射很慢,因为您正在查询程序集的元数据,而转换只是更改您引用的对象的类型。

程序集的元数据是有用的信息存储,但该信息最好在编译时而不是在执行时使用。编译器使用该元数据进行静态类型检查(除其他外)。您正在使用相同的元数据在执行时查找类型信息(如果您别无选择,这很好),这比转换要慢得多。

关于c# - 为什么在 .NET 中转换比反射快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1075585/

相关文章:

c# - "... an error occured while updating the object context. The ObjectContext might be in an inconsistent state...."

c# - .NET 最大内存使用 2GB,即使对于 x64 程序集也是如此

c# - 将注册表中的版本号转换为System.Version?

java - 从 JAR 文件中的类获取值

php - 在不使用反射的情况下获取类名减去命名空间

c# - 将具有不规则长度字节数组的 IObservable<byte[]> 转换为具有常规长度数组的 IObservable<byte[]>

c# - 在 WPF 中获取 MainWindow 的句柄

c# - XmlDocument 和 XDocument 处理之间的区别 &#x0;

java - 使用反射方法检索类的通用参数是否保证有效(在我的例子中)?

C# 动态函数 AmbigiousMatchException?