0

What is the best practice when reassigning object variables, to maximise memory and CPU efficiency?

We all know object variables do not actually "contain" the object data, but they're just references.

If an object variable is reassigned, I understand the object data gets automatically cleaned up by some garbage collector, otherwise it would remain inefficiently "lost in the memory". Is this correct? And in the first case, is the cleanup process efficient? To make things more clear, let's consider this simple example:

list1 = list(range(0, 1000))  #Some long list
list2 = list(range(0, -1000, -1))   #Some other long list
list1 = list2

Now, list 1 references same object data of list 2, but what happens to the data previously referenced by list1 (with no variable referencing it anymore)? Would it be more efficient to explicitly erase the object before?

del list1
list1 = list2
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    Also related: [Would you prefer using del or reassigning to None (garbage collecting)](https://stackoverflow.com/q/6693946/11082165) and [How can I explicitly free memory in Python?](https://stackoverflow.com/q/1316767/11082165) – Brian61354270 Feb 10 '23 at 16:54
  • TL;DR: there is no difference between `del list1` and rebinding `list1` for garbage collection purposes. As for whether the memory associated with `list1` will be freed, that depends on what Python implementation you're using, and whether any other references to `list1` exist (which can occur in surprising ways in richer interactive environments like IPython or Jupyter) – Brian61354270 Feb 10 '23 at 16:58

0 Answers0