how to avoid checking the same condition repeatedly ?

Piet van Oostrum piet at vanoostrum.org
Mon Oct 28 14:31:59 EDT 2013


Wolfgang Maier <wolfgang.maier at biologie.uni-freiburg.de> writes:

> Dear all,
> this is a recurring programming problem that I'm just not sure how to solve
> optimally, so I thought I'd ask for your advice:
> imagine you have a flag set somewhere earlier in your code, e.g.,
>
> needs_processing = True
>
> then in a for loop you're processing the elements of an iterable, but the
> kind of processing depends on the flag, e.g.,:
>
> for elem in iterable:
>     if needs_processing:
>         pre_process(elem)  # reformat elem in place
>     print(elem)
>
> this checks the condition every time through the for loop, even though there
> is no chance for needs_processing to change inside the loop, which does not
> look very efficient. 

I bet in most cases you won't notice the time used to check the condition.
Beware of premature optimization!
-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list