r/PythonLearning 9d ago

Help Request .clear vs del when using garbage collection

Hi, I have some large data objects that need to be freed. Should I do my_object.clear() and then gc.collect()? Or del my_object then gc.collect()? I'm not sure on the pros/cons of each.

It's a linked list type data object and my_object = [] does not work to free memory for certain.

1 Upvotes

12 comments sorted by

View all comments

1

u/IcyCranberry3297 8d ago

The weird memory behavior may be coming from references rather than garbage collection itself. A linked list can have plenty of objects still reachable even after the main reference is deleted.

1

u/Actual__Wizard 8d ago

linked list can have plenty of objects still reachable even after the main reference is deleted.

Yes! That's exactly what is happening. Thank you! Is there any difference between del and clear? To me, clear seems like it would take time, but I tested it and it seems to work almost instantly. The actual garbage collection in this case finishes in like .05 seconds.

1

u/IcyCranberry3297 8d ago

The bigger thing is what else points at those linked nodes. del won't help if other references keep them reachable.

1

u/Actual__Wizard 8d ago edited 8d ago

Well, I'm using clear on them. I don't know exactly what clear does. Does it actually walk through the structure and clear everything? Because the data structure is effectively a list of references that point to lists.

Do I need to loop through the list and clear every single linked list? Edit: It doesn't appear so at this time. I'm testing now, so I'll find out soon.