Twistios_Player
Twistios_Player

Reputation: 444

How to optimize if-statements in Python: First the more likely case or the more expensive one?

I am currently optimising the code of my pygame-game and now I am playing around with optimising if-Statements. There are many loops so the if-statements does take computing power because of expensive funktions. Now I want to find out, how to write more efficient statements(for example based on how likely or how expensive the conditions are).

Example:

if prim(num) or num = 5:
   dostuff()

or

if num = 5 or prim(num):
   dostuff()

where prim() is an example of a more expensive funktion, that is more likely to evaluate to False. "num = 5" is a condition that is not so expensive but not so likely to evaluate to True.

My Question is: Which of the examples is better, and are there other possibilities to improve if-Statements (for performance)?

Upvotes: 1

Views: 781

Answers (2)

LoW
LoW

Reputation: 604

You could collect data on multiple runs and evaluate the probability of each condition of being met, along with its average execution time.

If you have the two conditions c1 and c2, their probabilities of being true p1 and p2, along with their average time to run t1 and t2, then you can estimate the average required time to execute depending on the order of the evaluation:

  • First evaluating c1, then c2: t1 + (1-p1)*t2
  • First evaluating c2, then c1: t2 + (1-p2)*t1

Then you know which option is on average faster.

Upvotes: 1

Prune
Prune

Reputation: 77880

First of all, if prim is likely to be False, then you certainly want it as the second condition. Only when it's likely to evaluate to True, do you want it to lead the or compound: a False result guarantees that you must evaluate the other expression.

That said, there's no trivial rule: you need to determine the effective value of the ordering: the time spent on each evaluation multiplied by the likelihood that it will short-circuit the evaluation, factoring in the time saved.

In this case, num == 5 (note the comparison operator, rather than assignment) is so cheap that it's highly likely to be the one you want first. This depends on the probability that it will be True, and the relative time saving over calling prim.

Upvotes: 0

Related Questions