Garbage collection of local variables in __init__

Viewed 44

Context

I've been doing some experiments with TensorFlow and Keras. At some point, I've had a class like

class Foo:
    def __init__(self, **kwargs):
        bar = self.generate_bar(**kwargs)
        self.baz = self.generate_baz_from_bar(bar)
        ...

After some experiments, I realized that this implementation was slow, and after trying different things I discovered the following implementation was x5 faster

class Foo:
    def __init__(self, **kwargs):
        self.baz = self.generate_baz_from_bar(self.generate_bar(**kwargs))
        ...

Notice the only thing I did was to move the computation of bar inside self.generate_baz_from_bar.

Question

My intuition is that in the first case the variable bar is stored inside the Foo objects and carried through all the processes -notice that bar can be a heavy object-, thus slowing down everything. While in the second case, since no bar variable is defined the Foo objects are "lighter" and then the process is faster.

Then, my questions are:

  1. Is my intuition right? are the contents of variable bar stored inside the Foo instances?

  2. Does python do some kind of garbage collection for local variables defined inside __init__? For me, it would make sense to remove this object from there, since they can't be accessed. However, maybe I'm missing something and in some cases maybe it makes sense to keep those local variables in the __init__.

Thank you very much for your help!

0 Answers
Related