Home > Software design >  How is computation time affected by calculating comparison values before if statements?
How is computation time affected by calculating comparison values before if statements?

Time:05-27

I am currently writing a simulation framework in python, which will then moved to C.

Assume that I need 8 comparisons for further evaluation.

A=q<x<r
B=q<y<r
C=q<z<r
D=q<t<r

if C:
    if A:
        AC
    elif B:
        BC
    else:
        C
elif D:
    if A:
        AD
    elif B:
        BD
    else:
        D
elif A:
    A
else:
    B

A, B, C, D are all booleans. I assume that this is much faster than calling q<x<r for A, q<y<r for B and so on.

My questions are:

  1. Is if A: also called a comparison? Does it have a specific name?
  2. How does replacing nested ifs with if A and C: statements impact the computational time?

I apologise if I ask a stupid question, I don't know the keywords to search at the moment to check if this is duplicate.

Thanks in advance.

CodePudding user response:

Is if A: also called a comparison? Does it have a specific name?

Well, I don't know if it has a dedicated name. I'd call A an identity expression and the If statement evaluates its truth value. At least that last part is what the documentation calls it

How does replacing nested ifs with if A and C: statements impact the computational time?

Python's bytecode compiler doesn't do many optimizations. What you write is what you get. Some exceptions apply, for example a while True loop does not actually test the truth value of True, it just compiles to an infinite loop.

In your case you should note that you do comparisons that you don't necessarily need. If C is true, you wouldn't have had to test D. So only do this kind of stuff if it helps you avoid redundant comparisons.

As far as the difference between if A: if B: and if A and B:: There is none, assuming the resulting control flow is the same. Remember that boolean expressions are short-circuited. In Python bytecode, both would look roughly like this:

LOAD_FAST 1 (A)
POP_JUMP_IF_FALSE <else-branch>
LOAD_FAST 2 (B)
POP_JUMP_IF_FALSE <else-branch>
<insert-if-branch-here>
  • Related