加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:27:48 所属栏目:百科 来源:网络整理
导读:使用typeof(String)vs System.Type.GetType(“System.String”)是否具有显着的性能优势? 如果有的话,我想知道原因. 尽可能深入CLR以证明它. 我的测试显示是,差不多. 版本2 结果 配置=释放 baseline: 5572 ticks 2 mstypeof(Test): 8757 ticks 3 msType.GetT
使用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功能用作您想要进行基准测试的值的接收器.缺点是您现在正在对功能调用成本进行基准测试,但它们很小.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读