Performance overhead for properties in .NET

前端 未结 9 1948
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 01:43

I read somewhere that having public properties is preferable to having public members in a class.

  1. Is this only because of abstaraction and modularity? Are

9条回答
  •  甜味超标
    2020-12-10 02:11

    Is this only because of abstaraction and modularity? Are there any other over-riding reasons?

    Not that I know of; these reasons are by themselves compelling enough. But maybe someone else will jump in on this.

    The property accesses are conerted into function calls by the compiler. For properties without a backup store (e.g. public string UserName { get; set; }), what would be the performance overhead compared to a direct member access? (I know it shouldn't usually make a difference but in some of my code, properties are accessed millions of times.)

    In the resulting Intermediate Language, a property access is translated to a method call. However, as the word says, this is only an Intermediate Language: it gets compiled Just-In-Time down to something else. This translation step also involves optimizations like inlining of trivial methods, such as simple property accessors.

    I would expect (but you'd need to test to make sure) that the JITter takes care of such accessors, so there should be no performance difference.

提交回复
热议问题