Is the C# compiler smart enough to optimize this code?

前端 未结 6 809
无人及你
无人及你 2020-11-27 18:22

Please ignore code readability in this question.

In terms of performance, should the following code be written like this:

int maxResults = criteria.M         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 18:52

    It will be called and evaluated every time. The compiler has no way of determining if a method (or getter) is deterministic and pure (no side effects).

    Note that actual evaluation of the property may be inlined by the JIT compiler, making it effectively as fast as a simple field.

    It's good practise to make property evaluation an inexpensive operation. If you do some heavy calculation in the getter, consider caching the result manually, or changing it to a method.

提交回复
热议问题