You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#构造函数性能对比:默认值初始化vs手动显式赋值

显式默认值赋值vs自动默认值的性能差异

我碰到一段代码,在一个简单类的构造函数里给字段显式赋了默认值。既然字段本来就会被自动设为默认值,我想知道删掉这些显式赋值能不能提升性能?

我定义的类如下:

class RatherSimpleClass
{
    public int myNumber;
    public String myName;
    public bool myBool;
}

我想知道下面示例里创建s2的性能是不是比s1更好?我预期第二种写法性能略优,但不确定怎么正确测量,同时也想了解相关的最佳实践是什么?

RatherSimpleClass s1 = new RatherSimpleClass
{
    myNumber = 0,
    myName = null,
    myBool = false,

};
RatherSimpleClass s2 = new RatherSimpleClass { };

在看到JonasH的回答后,我做了如下性能测试:

int iterations = 1_000_000_000;
while (true)
{
    s.Start();
    for (int i = 0; i < iterations; i++)
    {
        RatherSimpleClass rsc = new()
        {
            myNumber = 0,
            myName = null,
            myBool = false
        };
    }
    s.Stop();
    Console.WriteLine($"explicit:	{s.ElapsedMilliseconds}");
    s.Reset();
    s.Start();
    for (int i = 0; i < iterations; i++)
    {
        RatherSimpleClass rsc = new();
    }
    s.Stop();
    Console.WriteLine($"autodefault:	{s.ElapsedMilliseconds}");
    s.Reset();
}

测试输出结果如下:

explicit:       6106
autodefault:    5415
explicit:       5814
autodefault:    5481
explicit:       5702
autodefault:    5507
explicit:       5761
autodefault:    5517
...

从测试结果推测,使用自动默认值初始化的性能大概比显式赋值快10%。

内容的提问来源于stack exchange,提问作者Schurl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 18:53:08