Best Practice on IF/ELSE Statement Order

前端 未结 10 2261
陌清茗
陌清茗 2020-12-16 14:48

Which is a better practice? (I\'m coding in .Net if that makes a difference)

IF condition = true THEN
   ...true action--even if rare...
ELSE
   ...action
E         


        
10条回答
  •  感动是毒
    2020-12-16 15:25

    You have received some pretty good answers already. I'm going to approach the question from a different angle.

    First, as far as performance goes it may not matter as much as you think in modern CPUs. That's because they use a feature called branch prediction in which the CPU attempts to predict the most likely direction the code will take. Of course, I still agree that you should place the most likely branch at the top if performance is your main concern.

    Second, I prefer readability over trivial performance enhancements. In most cases the benefit of readability outweigh those of performance.

    Third, use guard clauses when possible. It makes the code more readable.

提交回复
热议问题