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

前端之家收集整理的这篇文章主要介绍了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功能用作您想要进行基准测试的值的接收器.缺点是您现在正在对功能调用成本进行基准测试,但它们很小.

猜你在找的C#相关文章