I have this code
void test()
{
If (condition)
{
doSomthing();
}
}
test();
doSomethingMore();
Is there any performance effect with change it to:
void test()
{
If (!condition)
{
return;
}else
doSomthing();
}
}
test();
doSomethingMore();
Why??
You’re really asking the wrong question. The performance is completely irrelevant here. Any optimizing compiler will render it absolutely insignificant, probably producing exactly the same binary for both styles.
No, in fact the real question is which code snippet is more readable. Your fellow human beings are the ones who will have to read and understand your code later. And, if you’re particularly unlucky, one of those human beings that will have to read and understand your code later might even be you. Thus, it’s far more important to write code that is logically structured and easily readable than it is to worry about micro-optimizations like this. Let the compiler handle those.
So, which is more readable? Definitely the first one. If the
conditionis true, then you’re going to call thedoSomething()function. Far more understandable.In general,
ifstatements should evaluate positively-named conditions. Most of the time, you should try to avoid the!sign, as it’s easily missed when scanning the code and can potentially make your code read as a double-negative. You also should generally avoid having multiple exit points from functions (i.e., thereturnstatement). You should be able to read the function from top-to-bottom and see exactly what it does, without having to jump around. The second code snippet violates both of these rules, and does little else to help justify preferring it over the first.