0

Just had to decompile my old code and i'm used to write it this way:

if(!x)
{
  DoSth();
}

but the decompiler always wrote it this way if there is no code after the snippet:

if(x)
{
  return;
}

DoSth();

Is there any performance advantage in calling return like in the lower code snippet or is it just a personal preference thing?

Leppin
  • 1
  • 1
    Possible duplicate of ["equal to" versus "not equal to" operators in an if-else statement](https://stackoverflow.com/questions/40036165/equal-to-versus-not-equal-to-operators-in-an-if-else-statement) – phuclv Aug 29 '18 at 09:34
  • [Is `if(var == true)` faster than `if(var != false)`?](https://stackoverflow.com/q/3818933/995714), [What is the effect of ordering if...else if statements by probability?](https://stackoverflow.com/q/46833310/995714), [Fastest/Proper way of ordering if/else if statements](https://stackoverflow.com/q/7262103/995714) – phuclv Aug 29 '18 at 09:35
  • 1
    From [one of the answers on the above question](https://stackoverflow.com/a/3819132/4756299): "If you care about performance, *use a profiler* and *find the slowest thing* and then *fix that*. It makes no sense whatsoever to be worried about nanosecond optimizations when you probably are wasting entire milliseconds somewhere else in your program." – Andrew Henle Aug 29 '18 at 10:26
  • That's correct, but i always want to use the best practice solution for as much of my code as possible. And the snippet above is used pretty often in different programs so if there's any performance difference and i'll fix that it'll improve all my future code. – Leppin Aug 29 '18 at 10:48
  • [Should I return from a function early or use an if statement?](https://softwareengineering.stackexchange.com/q/18454/98103), [If statement vs if-else statement, which is faster?](https://stackoverflow.com/q/43202012/995714) – phuclv Aug 29 '18 at 14:36
  • There's no best practice here. Write whatever is readable. In rare cases that the if block is entered millions of times that may affect performance, use [`likely/unlikely/__builtin_expect`](https://stackoverflow.com/q/1440570/995714) if you know one branch has higher probability. Otherwise do a profile to make sure that the order is important. [Optimizing a branch for a known more-common path](https://stackoverflow.com/q/35938249/995714). [In C++20 you also get `[[likely]]/[[unlikely]]` function attributes](https://stackoverflow.com/q/51797959/995714) – phuclv Aug 29 '18 at 14:41
  • Thats some interesting points described in the named links, thank you for sharing them. – Leppin Aug 29 '18 at 15:05

0 Answers0