Reputation: 10155
So, two cases:
Case1:
if (doSomething) doFunction();
//...
void doFunction() {
// ... do something time consuming
}
Case 2:
doFunction();
//...
void doFunction() {
if (!doSomething) return;
// ... do something time consuming
}
This is within extremely time sensitive environment (roughly 0.1 ms would make a big difference); doFunction()
is called quite often (order of ~100 times) and most often than not, doSomething
is false. It seems obvious that case 1 would be more efficient, but by how much? Or would it not make a difference (on the order of 0.01 ms)?
Upvotes: 1
Views: 88
Reputation: 10553
A function call involves putting stuff on the stack frame, and later popping that stuff back off when you call return. Both of them involve a conditional jmp
(jump), so that does not impact performance. I would go with the first approach.
Upvotes: 1
Reputation: 41822
Case 1 would be more efficient. The magnitude of the difference will be tiny; we're talking about the difference between one instruction and a couple of instructions - so on any machine that can do a few million instructions per second, that's insignificant.
The first case would (typically) be implemented by a single conditional jump instruction.
In the second case, the overhead of the function call is always present in addition to the conditional jump.
It may be the case that the compiler will optimize the second case anyway, making them equivalent. You can check by looking at the compiler output, or by timing it yourself.
Upvotes: 4