微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – typeof(String)与System.Type.GetType(“System.String”)的性能

使用typeof(String)vs System.Type.GetType(“System.String”)是否具有显着的性能优势?

如果有的话,我想知道原因.
尽可能深入CLR以证明它.

我的测试显示是,差不多.

版本2

结果

配置=释放

baseline: 5572 ticks 2 ms
typeof(Test): 8757 ticks 3 ms
Type.GetType(String): 3899966 ticks 1482 ms

[MethodImpl(MethodImplOptions.NoInlining)]
static int Call(Type t)
{
    return 1;
}
static void Main(string[] args)
{
    const int Iterations = 1000000;
    int count;

    Stopwatch sw = Stopwatch.StartNew(); count = 0;
    for (int i = 0; i < Iterations; i++)
    {
        count += Call(null);
    }
    sw.Stop();
    Console.WriteLine("baseline: {0} ticks {1} ms",sw.ElapsedTicks,sw.ElapsedMilliseconds);

    sw = Stopwatch.StartNew(); count = 0;
    for (int i = 0; i < Iterations; i++)
    {
        count += Call(typeof(String));
    }
    sw.Stop();
    Console.WriteLine("typeof(Test): {0} ticks {1} ms",sw.ElapsedMilliseconds);

    sw = Stopwatch.StartNew(); count = 0;
    for (int i = 0; i < Iterations; i++)
    {
        count += Call(Type.GetType("System.String"));
    }
    sw.Stop();
    Console.WriteLine("Type.GetType(String): {0} ticks {1} ms",sw.ElapsedMilliseconds);
}

版本1

结果

配置=调试

typeof(Test): 24782 ticks 9 ms
Type.GetType(String): 4783195 ticks 1818 ms

static void Main() 
{
  const int Iterations = 1000000;
  Stopwatch sw = Stopwatch.StartNew();
  for (int i = 0; i < Iterations; i++)
  {
    Type t = typeof(String);
  }
  sw.Stop();
  Console.WriteLine("typeof(Test): {0} ticks {1} ms",sw.ElapsedMilliseconds);

  sw = Stopwatch.StartNew();
  for (int i = 0; i < Iterations; i++)
  {
    Type t = System.Type.GetType("System.String");
  }
  sw.Stop();
  Console.WriteLine("Type.GetType(String): {0} ticks {1} ms",sw.ElapsedMilliseconds);
}

解决方法

你回答了自己的问题. typeof(string)更快.但看到原因很有意思.

typeof被编译为ldtoken和GetTypeFromHandle(见Efficiency of C#’s typeof operator (or whatever its representation is in MSIL)).这比GetType(“System.String”)更有效.

另请注意,版本1中的基准测试无效,因为未使用结果变量Type t.不使用局部变量将导致JIT优化语句.第一个循环体实际上是无操作,但第二个循环将执行.根据您报告的性能数据,这是我的猜测.

Here’s a benchmark done right. NoInline功能用作您想要进行基准测试的值的接收器.缺点是您现在正在对功能调用成本进行基准测试,但它们很小.

原文地址:https://www.jb51.cc/csharp/243661.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐