[Python-Dev] python optimization
bcannon at gmail.com
Thu Sep 15 20:13:02 CEST 2005
On 9/15/05, Neal Becker <ndbecker2 at gmail.com> wrote:
> I use cpython. I'm accustomed (from c++/gcc) to a style of coding that is
> highly readable, making the assumption that the compiler will do good
> things to optimize the code despite the style in which it's written. For
> example, I assume constants are removed from loops. In general, an entity
> is defined as close to the point of usage as possible.
> I don't know to what extent these kind of optimizations are available to
> cpython. For example, are constant calculations removed from loops?
If you mean ``2+3``, then yes. If you mean ``2 + a`` where is a loop
invariant, then no.
> about functions?
No optimization there.
> Is there a significant cost to putting a function def
> inside a loop rather than outside?
If you put it in a loop then the function must be reconstructed every
time through the loop. I have never benchmarked the cost of function
construction but I doubt it's cheap.
The problem with all of these optimizations that you can do in more
static languages is you get to assume most things do not change from
underneath you. In Python, thanks to threading, access to frames,
global namespaces of modules, etc., most things cannot be naively
optimized without a lot of checking up front to make sure the
optimization is valid every time it is run. If you want some gruesome
detail, you can read my thesis (http://www.drifty.org/thesis.pdf) and
the section on problems with introducing type inference into Python.
More information about the Python-Dev