Actual Performance of Fields vs. Properties

孤街浪徒 提交于 2019-11-28 12:09:39

When developing the math library for SlimDX, we found that, on pre-.NET 3.5 SP1 frameworks, using fields for the members of the math types (such as X, Y, Z for a Vector3) gave a disproportionate performance increase over properties. In other words, the difference was noticeable for small math functions which heavily accessed properties.

This has since been improved since .NET 3.5 SP1 (see JIT inling). While I believe that the JIT prior to that will still inline small methods (properties are simply methods after all), there is a bug in the earlier frameworks that prevented inlining of methods that take or return value types.

Note that the difference, when there, is still quite small. I would still elect to use properties in all but the most performance critical cases.

The C# compiler won't optimize this, no - but the JIT compiler can usually inline trivial (and non-virtual) properties as far as I'm aware.

As with all performance questions though: when in doubt, test!

The effect is minor in either direction. If your properties look like this::

public static SomeType PropertyName
{
    get {return MyType.propertyName;}
    set {MyType.propertyName = value;}
}

There genuinely should be a very minor difference. The Jit compiler should inline the call MyType.set_Property into a field load, but even if it couldn't due to a bug. I'd personally err on the side of caution and stick with the property setters and getters as potentially the method body might change, and as a result the raw field access/mutation may not be enough.

If you'd like to test you can force the method you emit to use the MethodImpl that turns off inlining or optimizing. And then compare the difference, I really doubt it'll be significant.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!