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?
4
You shouldn’t check it — not because it is more expensive to do so (given todays cpu’s that is by no means certain), but because it is conceptually unnecessary. Adding it makes the code harder to reason about.
All code should serve a purpose, when reading the code we not only interpret it, we also try to extract that purpose — to understand both what it is doing, and why.
Code which serves no purpose is thus a hinderance. It can cause considerable delays as a purpose is sought — and of course not found.
If, in a specific case, you were to profile the code, find a significant performance impact, then you could add the check, with an appropriate comment (said comment to include compiler and version tested).
1
Setting a boolean variable is a vanishingly small cost in most programming languages. Don’t check it first to see if it’s set; just set it.
1
If setting the boolean is the only reason for the loop then you may just as well break out of it when setting the boolean:
balance_null = True
while (crazy_loop()):
...
if 0.0 < balance:
balance_null = False
break;
or extract the loop to a function and use early return.
2