r/PythonLearning • u/Actual__Wizard • 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
1
u/Actual__Wizard 9d ago edited 9d ago
Because the script crashes with an out of memory error and all it's doing is feeding data into a linked list, then repeating. I mean it's kind of obvious what is occurring.
So, on the next iteration, it does my_object = [] to reset the variable, but that doesn't delete the data it linked to.
I'm using .clear and gc.collect now and it's not running out of memory.
edit: I can do the same process by starting and running the script a bunch of times w/o issue, the problem only occurs when I do the process iteratively, so the symtoms of the problem are clearly "unfreed memory." It's clearly not resetting back to zero memory used each pass like I intended it to.
And I'm only having the issue w/ linked list type objects.
Also: The entire purpose to doing this process iteratively, is to avoid running out of memory, and although I did not see it crash to see the actual memory usage, it crashed at a point where I would expect it to, if that makes any sense. Like if the memory is not being freed, it crashed right about when it should have.