.NET中属性的性能开销

apo*_*020 21 .net c# performance

我在某个地方读到,拥有公共财产比在一个班级中拥有公共成员更可取.

  1. 这只是因为抽象和模块化吗?还有其他任何超越原因吗?

  2. 属性访问由编译器转换为函数调用.对于没有备份存储的属性(例如public string UserName { get; set; }),与直接成员访问相比,性能开销会是多少?(我知道它通常不会有所作为,但在我的一些代码中,属性被访问了数百万次.)

Edit1:我在整数成员和属性上运行了一些测试代码,公共成员的速度是属性的3-4倍.(在调试中~57 ms.vs~206 ms.在Release中57与97 vs. 97是最常见的运行值).对于1000万次读写,两者都足够小,不足以证明改变任何东西.

码:

    class TestTime1
{
    public TestTime1() { }
    public int id=0;
}
class TestTime2
{
    public TestTime2() { }
    [DefaultValue(0)]
    public int ID { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        try
        {
            TestTime1 time1 = new TestTime1();
            TestTime2 time2 = new TestTime2();
            Stopwatch watch1 = new Stopwatch();
            Stopwatch watch2 = new Stopwatch();
            watch2.Start();
            for (int i = 0; i < 10000000; i++)
            {
                time2.ID = i;
                i = time2.ID;
            }
            watch2.Stop();
            watch1.Start();
            for (int i = 0; i < 10000000; i++)
            {
                time1.id = i;
                i = time1.id;
            }
            watch1.Stop();
            Console.WriteLine("Time for 1 and 2 : {0},{1}",watch1.ElapsedMilliseconds,watch2.ElapsedMilliseconds);

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.In.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 21

连续运行测试20次,确保在发布版本中启用了JIT优化:

Time for 1 and 2 : 47,66
Time for 1 and 2 : 37,42
Time for 1 and 2 : 25,36
Time for 1 and 2 : 25,25
Time for 1 and 2 : 27,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 26,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Time for 1 and 2 : 25,25
Run Code Online (Sandbox Code Playgroud)

是的,抖动擅长内联属性访问.Perf是一个非问题,永远不应该考虑.

  • 我也是32位,我假设我们使用相同的JITter.工具+选项,调试,常规,取消选中"抑制模块加载时的JIT优化". (3认同)

Ste*_*dit 18

不要担心性能开销.它是如此轻微,你不应该考虑削弱类的封装; 这将是最糟糕的过早优化.


Tho*_*mas 9

这只是因为抽象和模块化吗?还有其他任何超越原因吗?

从来没听说过; 这些原因本身就足以引人注目.但也许其他人会加入这个.

属性访问由编译器转换为函数调用.对于没有备份存储的属性(例如,公共字符串UserName {get; set;}),与直接成员访问相比,性能开销会是多少?(我知道它通常不会有所作为,但在我的一些代码中,属性被访问了数百万次.)

在生成的中间语言中,属性访问被转换为方法调用.但是,正如单词所说,这只是一种中间语言:它将及时编译为其他内容.此转换步骤还涉及优化,如内联简单的方法,如简单的属性访问器.

我希望(但你需要测试以确保)JITter负责这样的访问器,因此应该没有性能差异.

  • 标准规定这是有原因的,我认为这是我们正在寻找的原因,而不是"因为微软这么说":) (7认同)
  • 这是关于内联问题的更权威的答案(有链接):http://stackoverflow.com/questions/646779/does-c-inline-properties/646780#646780 (2认同)