[Tutor] rationale for nested classes?

Mac Ryan quasipedia at gmail.com
Mon Aug 17 23:04:51 CEST 2009


On Mon, 2009-08-17 at 13:33 -0400, Kent Johnson wrote:
> On Mon, Aug 17, 2009 at 1:12 PM, Mac Ryan<quasipedia at gmail.com> wrote:
> 
> > Finally, I somewhere read that embedded declarations are much faster
> > than external ones in being referenced. So, if performance is an issue,
> > maybe embedding one class within another one might bring you some
> > benefit rather than having an object instantiated from the first class
> > having to reference a class which is external to its generating one.
> > [Hope that is understandable... English is not my first language... :)]
> 
> *Local* variables are faster than variables that must be looked up.
> Nested classes would not qualify for this.

I could not find the article I was referring to, so I ran a test myself,
and - surprisingly - I found out the exact contrary of what I read.
Nesting the class lower the performance of nearly 10%.

FLAT: [4.0505850315093994, 4.0618939399719238, 4.0537300109863281]
<code>
import timeit

class Printer(object):

  def __init__(self):
    a = 3 ** 3

class Embedder(object):

  def __init__(self):
    for i in range(10000):
	a = Printer()

if __name__ == '__main__':
  timer = timeit.Timer("new = triedout.Embedder()", "import triedout")
  print timer.repeat(3, 1000)
</code>

NESTED: [4.3873238563537598, 4.3799960613250732, 4.3729050159454346]
<code>
import timeit

class Embedder(object):

  class Printer(object):

    def __init__(self):
      a = 3 ** 3

  def __init__(self):
    for i in range(10000):
	a = self.Printer()

if __name__ == '__main__':
  timer = timeit.Timer("new = triedout.Embedder()", "import triedout")
  print timer.repeat(3, 1000)
</code>




More information about the Tutor mailing list