Actual Performance of Fields vs. Properties

前端 未结 3 1604
慢半拍i
慢半拍i 2020-12-11 04:01

I\'m doing some post-build CIL weaving that adds CIL to all methods in an assembly (in other words tons of methods). Each method checks if a specific value is null. Example

3条回答
  •  盖世英雄少女心
    2020-12-11 04:33

    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.

提交回复
热议问题