optimization

Terry Reedy tjreedy at udel.edu
Mon Dec 1 19:59:51 CET 2008


skip at pobox.com wrote:
>     Neal> I noticed in some profiling, that it seems that:
> 
>     Neal> def Func ():
>     Neal>   def something():
>     Neal>     ...
> 
>     Neal> It appears that if Func is called many times, this nested func
>     Neal> definition will cause significant overhead.  Is this true?  I
>     Neal> guess I've become accustomed to decent compilers performing
>     Neal> reasonable transformations and so have tended to write code for
>     Neal> clarity.
> 
> It could.  OTOH, the code object which implements the something body is
> stored as a local var (or a constant, can't remember off the top of my
> head), so it's not compiled over and over again.

Constant.  With 3.0...

 >>> def f():
	def g():
		pass

	
 >>> import dis
 >>> dis.dis(f)
   2           0 LOAD_CONST               1 (<code object g at 
0x0137D920, file "<pyshell#4>", line 2>)
               3 MAKE_FUNCTION            0
               6 STORE_FAST               0 (g)
               9 LOAD_CONST               0 (None)
              12 RETURN_VALUE

If the inner function is constant and does not directly access outer 
function locals, and if every last tick of speed is a concern, then it 
can be move out and given a name like _outer_helper.

I would go for clarity and correctness first, but I would also wonder 
whether an inner function that is independent of its setting and 
therefore movable might be turned into something of more general use and 
usefully moved out for purposes other than just speed.

Terry Jan Reedy







More information about the Python-list mailing list