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

前端 未结 6 834
无人及你
无人及你 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 19:12

    why not test it?

    just set up 2 console apps make it look 10 million times and compare the results ... remember to run them as properly released apps that have been installed properly or else you cannot gurantee that you are not just running the msil.

    Really you are probably going to get about 5 answers saying 'you shouldn't worry about optimisation'. they clearly do not write routines that need to be as fast as possible before being readable (eg games).

    If this piece of code is part of a loop that is executed billions of times then this optimisation could be worthwhile. For instance max results could be an overridden method and so you may need to discuss virtual method calls.

    Really the ONLY way to answer any of these questions is to figure out is this is a piece of code that will benefit from optimisation. Then you need to know the kinds of things that are increasing the time to execute. Really us mere mortals cannot do this a priori and so have to simply try 2-3 different versions of the code and then test it.

提交回复
热议问题