A better self

Terry Reedy tjreedy at udel.edu
Fri Jul 19 13:39:20 EDT 2002


"Louis M. Pecora" <pecora at anvil.nrl.navy.mil> wrote in message
news:190720021018041866%pecora at anvil.nrl.navy.mil...
> Many people have suggested doing something like the following (which
is
> reasonable) to eliminate self. from mathematical expressions:
>
>   t, x, y, z=self.t, self.x, self.y, self.z
>   result=sin(t)*x**y+sqrt(z)  # A pretend formula
>
> My question is how much overhead is added by the assignments in the
top
> line?  I suspect not much at all, but then I do not know how the
> interpreter handles these things.

You are correct.  Reference to local variables is optimized to be fast
via array lookup*.  If you use a variable at least twice (as in
quadratic formula, for example), you might actually gain by copying to
a local.  Certainly, copying a global or builtin method to a local for
repeated use is a standard Python speedup trick.

Note that when you do the copying, you can also rename, thus allowing
both self-explanatory attribute names and short formulas in standard
form.  Consider

  def mortgage_pay(self):
    i = self.interest_rate
    n = 12*self.years
    p = self.principal
    return <standard formula using i, n, and p>

Terry J. Reedy

* IE, when "meth(self, a): b = self.attr; return (a+math.sin(b))/b" is
compiled names 'self', 'a', and 'b' become slots 0, 1, and 2 in a
behind-the-scenes localvars array.  There is no runtime dict lookup as
there is for globals and self attributes.






More information about the Python-list mailing list