1

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)?

3
  • 3
    Run both through a profiler, then you'll get your answer. Commented Aug 25, 2011 at 2:26
  • I wish it's that simple... also I want to know what g++ might do in this situation Commented Aug 25, 2011 at 2:28
  • @polyglot: I tried very simple versions of your two cases with g++ and got pretty much identical results. I suspect it's smart enough to optimise the second case. Commented Aug 25, 2011 at 2:47

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Except if the function gets inlined. Then it's pretty much the same.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.