0

If I were to run

class Myclass():
    def __init__(self, value):
        self.value = value

var1 = Myclass(1) # initializes the first instance of Myclass
var1 = Myclass(2) # initializes the second instance of Myclass

would the first instance of Myclass linger around in memory? Would the garbage collector (?) free up the space? Do I have to call del var1 to properly free the memory at runtime?

The background of my question is that I run a large loop where in every iteration I need a different instance of a specific class. While I call del explicitly at the moment, it would be nice to know the default behaviour.

Neuneck
  • 294
  • 1
  • 3
  • 14

2 Answers2

3

TL;DR: Overwriting var1 with a new object will decrease the reference counter of the original object referenced by var1. If the reference count of an object is zero, the object is destroyed (according to this answer).

The actual answer is a lot more complex than this, and I don't think I feel comfortable delving too much in depth with the explanation (hopefully someone will step in or point you to another question, I'm fairly certain this is a duplicate).

The problem is, Python's garbage collector is implementation-dependent and even in one implementation it can adopt different policies.

GPhilo
  • 18,519
  • 9
  • 63
  • 89
1

When you declaration a new instance your will got different memory space, you can simple check it by id() build-in function.

In [2]: id( Myclass(1))
Out[2]: 4481511576

In [3]: id( Myclass(1))
Out[3]: 4481591488

So, back to your question, if you run multi-times inside your loop. you have to alloc/dealloc memory each time! That's sadly, so if you really want keep the speed up. you can make your object as simple as you can by define __slots__ to keep your object simple even can be fly! check this how to play with slots

Frank AK
  • 1,705
  • 15
  • 28
  • But isn't it the garbage collector's job to recognize when I overwrite the access to an object (besides direct pointer handling) and free up that memory on the go? Of course there will be a new object created, but does the first object persist in memory? – Neuneck Jan 24 '18 at 13:52
  • @Neuneck The first instance will have ref-counter for GC used! you don't need to care about the memory-leak question! – Frank AK Jan 24 '18 at 13:55
  • @GPhilo Maybe no complete answer! he/she want to improve the speed of multi generate new object! – Frank AK Jan 24 '18 at 13:56