How smart is the Python interpreter?

Terry Reedy tjreedy at udel.edu
Fri Aug 1 00:00:36 EDT 2008



ssecorp wrote:
> def str_sort(string):
> 	s = ""
> 	for a in sorted(string):
> 		s+=a
> 	return s
> 
> 
> if i instead do:
> 
> def str_sort(string):
> 	s = ""
>         so = sorted(string)
> 	for a in so:
> 		s+=a
> 	return s
> 
> 
> will that be faster or the interpreter can figure out that it only has
> to do sorted(string) once? or that kind of cleverness is usually
> reserved for compilers and not interpreters?

The optimizations performed by a Python interpreter and where they are 
performed depend on the implementation and version.  CPython is 
conservative about optimizations.  Not only do the developers want to be 
sure they are 100% correct (unlike too many optimizing compilers), but 
Guido also rejects some that are too tricky and too fragile (easily 
broken by new maintainers).  In Python 3.0, here are two compiler 
optimizations

 >>> from dis import dis
 >>> def f(): return 1+2

 >>> dis(f)
   1           0 LOAD_CONST               3 (3)
               3 RETURN_VALUE

# constant arithmetic (folding); done with floats also

 >>> def f():
	a,b = 1,2
	return a+b

 >>> dis(f)
   2           0 LOAD_CONST               3 ((1, 2))
               3 UNPACK_SEQUENCE          2
               6 STORE_FAST               0 (a)
               9 STORE_FAST               1 (b)

   3          12 LOAD_FAST                0 (a)
              15 LOAD_FAST                1 (b)
              18 BINARY_ADD
              19 RETURN_VALUE

# tuples with constant members are pre-built by the compiler and stored
in the code object.  What you don't see (if it is still there) is an 
optimization in the interpreter loop for BINARY_ADD that takes a 
shortcut if both operands are ints.

tjr




More information about the Python-list mailing list