Sometimes I need to check some condition that does not change inside the loop, this means that the test is evaluated at each iteration, but I think this is the wrong way.
I thought, since the condition does not change inside the loop, I should check it only once outside the loop, but then I will have to "repeat myself" and, possibly, write the same loop more than once. Here is the code showing what I mean:
#!/usr/bin/python x = True
Running cProfile
in the previous code gave the following result:
ncalls tottime percall cumtime percall filename:lineno(function) 1 0.542 0.542 0.542 0.542 testloop.py:5(inside) 1 0.261 0.261 0.261 0.261 testloop.py:12(outside) 1 0.000 0.000 0.803 0.803 testloop.py:3(<module>)
This shows that, obviously, testing once outside the loop gives better performance, but I should have written the same loop twice (maybe more if there were several elif
s).
I know that this performance will not matter much in most cases, but I need to know what is the best way to write such code. For example, is there a way to tell python to check the test only once?
Any help is appreciated, thanks.
EDIT:
Actually, after some tests, I am now convinced that the difference in performance mainly depends on other code executed in the cycles, and not on the evaluation of the tests. Therefore, at the moment I stick to the first form, which is more readable and better debugged later.