0

In order to optimize for execution speed, it is recommended to avoid using if-conditions inside a loop. Imagine there is a case where loop unswitching is not possible, but information (or an estimate) about the frequency of the conditions is available.

Does the order of conditions in an if-else-statement influence execution speed?

Assume I now (or estimate) condition A occurs 80%, B occurs 15% and C only 5% and the times to calculate the conditions is equal. Would it the better to write the loop like this or does the order makes no difference in execution time?

for (i in N){
    if (A(i))
        foo(i)
    else if (B(i))
        bar(i)
    else
        foobar(i)
}

Are there any best practices regarding order of conditions? Is it language dependent? What if the time to evaluate conditions is not equal? Would it be the best to order the conditions from cheapest to most expensive in that case?

Tinu
  • 2,432
  • 2
  • 8
  • 20

1 Answers1

1

In theory, placing the most likely branch first should be fastest, because less conditions need to be checked. To exchange the order of checks, it is important that for all inputs i, exactly one of the possible conditions is fulfilled.

In practice, you will probably not be able to tell the difference in the performance, because of branch prediction, if you are using a compiled language. A great explanation was provided here. For interpreted languages, this aspect has probably no impact, because the interpreter needs anyway full instructions to read the text line so that the pipelining can't kick in anyway.

If your language features a switch statement, you should probably use it, because there the compiler knows better what it got, so it can pull out maybe some more tricks

schetefan24
  • 106
  • 1
  • 8
  • 1
    Do you think branch prediction is as effective with interpreted lanuages. – Tarik Nov 14 '20 at 13:32
  • no, in interpreted languages, branch prediction should not have a big impact (because they are slow anyway and need to parse the inputs first). But if you are asking about the performance of such small tweaks, I consider it unlikely that he uses an interpreted language. But good point, I add it to the answer. – schetefan24 Nov 14 '20 at 13:54