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

前端 未结 6 812
无人及你
无人及你 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:57

    Your two code samples are only guaranteed to have the same result in single-threaded environments, which .Net isn't, and if MaxResults is a field (not a property). The compiler can't assume, unless you use the synchronization features, that criteria.MaxResults won't change during the course of your loop. If it's a property, it can't assume that using the property doesn't have side effects.

    Eric Lippert points out quite correctly that it depends a lot on what you mean by "the compiler". The C# -> IL compiler? Or the IL -> machine code (JIT) compiler? And he's right to point out that the JIT may well be able to optimize the property getter, since it has all of the information (whereas the C# -> IL compiler doesn't, necessarily). It won't change the situation with multiple threads, but it's a good point nonetheless.

提交回复
热议问题