Optimizing constants in loops
Michael Hoffman
cam.ac.uk at mh391.invalid
Wed Jun 13 11:18:45 EDT 2007
The peephole optimizer now takes things like
if 0:
do_stuff()
and optimizes them away, and optimizes away the conditional in "if 1:".
What if I had a function like this?
def func(debug=False):
for index in xrange(1000000):
if debug:
print index
do_stuff(index)
Could the "if debug" be optimized away on function invocation if debug
is immutable and never reassigned in the function? When performance
really matters in some inner loop, I usually move the conditional
outside like this:
def func(debug=False):
if debug:
for index in xrange(1000000):
print index
do_stuff(index)
else:
for index in xrange(1000000):
do_stuff(index)
It would be nice if this sort of thing could be done automatically,
either by the interpreter or a function decorator.
--
Michael Hoffman
More information about the Python-list
mailing list