lundi 10 juin 2019

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

Aucun commentaire:

Enregistrer un commentaire