Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python if statement efficiency

Tags:

A friend (fellow low skill level recreational python scripter) asked me to look over some code. I noticed that he had 7 separate statements that basically said.

if ( a and b and c):     do something 

the statements a,b,c all tested their equality or lack of to set values. As I looked at it I found that because of the nature of the tests, I could re-write the whole logic block into 2 branches that never went more than 3 deep and rarely got past the first level (making the most rare occurrence test out first).

if a:     if b:         if c:     else:         if c: else:     if b:         if c:     else:         if c: 

To me, logically it seems like it should be faster if you are making less, simpler tests that fail faster and move on. My real questions are

1) When I say if and else, should the if be true, does the else get completely ignored?

2) In theory would

if (a and b and c)

take as much time as the three separate if statements would?

like image 668
Dennis Avatar asked Mar 29 '10 15:03

Dennis


People also ask

Is if-else efficient?

Efficient if-else Statements While in a serial if block, all the conditions are tested, in an if-else block the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.

Do many if statements slow down code?

So to answer your question: unless you have an ungodly number of conditionals that each require complicated calculations or have side effects, you can usually consider the quantity of them to be inconsequential. However, as others have noted, having too many if statements can reduce code readability.

Which is faster if or if-else?

In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.


1 Answers

I would say the single test is as fast as the separate tests. Python also makes use of so called short-circuit evaluation.

That means for (a and b and c), that b or c would not be tested anymore if a is false.

Similar, if you have an OR expression (a or b) and a is true, b is never evaluated.

So to sum up, the clauses don't fail faster with separation.

like image 86
Felix Kling Avatar answered Sep 22 '22 21:09

Felix Kling