dimanche 1 février 2015

Check a boolean before setting it in a loop, or just set it


I have a rather tight loop with the following check to see if balance had ever been positive:



balance_null = True

while (crazy_loop()):
...
if 0.0 < balance:
balance_null = False


In no place would balance_null ever be set back to True. Would the code be more efficient if I were to check the state of balance_null before setting it?



balance_null = True

while (crazy_loop()):
...
if 0.0 < balance and `balance_null`==True:
balance_null = False


The code example is in Python, but I am actually interested in the general case, which is why I'm not simply benchmarking it myself. What is considered a best practice, and what are the exceptions to the rule?





Aucun commentaire:

Enregistrer un commentaire