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

c# – 静态构造函数可以降低访问静态方法的性能吗?

发布时间:2020-12-15 08:29:49 所属栏目:百科 来源:网络整理
导读:第一次访问静态成员时会执行静态构造函数.知道了这一点,我有几个问题: 这是否意味着每次访问静态方法时,运行时必须检查是否已调用静态构造函数? 这是否会导致性能下降? “无构造函数”的静态类可以避免这种性能损失吗? [编辑]:我想澄清一点,我不关心微
第一次访问静态成员时会执行静态构造函数.知道了这一点,我有几个问题:

>这是否意味着每次访问静态方法时,运行时必须检查是否已调用静态构造函数?
>这是否会导致性能下降?
>“无构造函数”的静态类可以避免这种性能损失吗?

[编辑]:我想澄清一点,我不关心微优化.
我问这个问题,因为这是一个设计决定.如果静态构造函数会导致性能损失,那么我将考虑到这一点设计我的代码,并且会更加了解可能影响性能的决策.

这是一个例子来说明我的问题.采用Independent方法并将其置于单独的静态类中会有什么好处吗?这样,就不必检查静态测试是否已初始化. [更新请参阅下面的答案以获得更好,更简单的示例].

static class Test {
  // Static constructor with dependent method:
  static int x;
  static Test() { x = 5; }
  static int Dependent() { return x; }

  // Static,independent method:
  static int Independent(int y) { return y+1; }
}

关于静态构造函数的C#规范中的Here’s the quote:

The execution of a static constructor is triggered by the first of the
following events to occur within an application domain:

  • An instance of the class is created.
  • Any of the static members of the class are referenced.

解决方法

由于缺乏答案,在@ Jobo的指导下,我决定自己测试一下.

这是我的测试类:

static class WithConstructor {
    static WithConstructor(){ }
    public static int Square(int x){ return x*x; }
}
static class NoConstructor {
    public static int Square(int x){ return x*x; }
}

编译为Release,使用.NET 4.0,结果非常一致:

╔═════════════╦══════════════════╦═════════╦═══════════════╗
║ Iterations: ║ With Constructor ║ 4513 ms ║ Improvement:  ║
║ 1000000000  ║ No Constructor   ║ 3072 ms ║ 33%           ║
╚═════════════╩══════════════════╩═════════╩═══════════════╝

因此,我将回答我自己的问题:

>如果存在静态构造函数,则静态方法将导致(微观)性能损失,因为必须始终检查beforefieldinit标志.>如果不存在静态构造函数,则该方法不会导致性能损失.

(编辑:李大同)

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

    推荐文章
      热点阅读