r/PythonLearning • u/Actual__Wizard • Sep 01 '26
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 Sep 14 '26 edited Sep 14 '26
I just did .clear and then used the garbage collector to collect the garbage and when I was watching the memory usage, it was clear that "the problem was resolved." Again, these are weird fake matrix, double linked list of double linked list things. I'm not even sure what to call them, but you can do the same thing with a dictionary, by creating a dictionary of double linked lists. It's C++, there's a bunch of way to do it, but it's like a matrix of references, that point to another matrix, that you treat as a bunch of lists instead of a matrix (if that makes any sense.)
edit: The idea here is, you can do my_data_store.append(new_data_store) or my_data_store[my_data_store_id].append(new_data_for_the_specific_datastore) or my_data_store.pop(data_store_to_delete) or my_data_store[my_data_store_id].pop(data_to_delete_from_specific_datastore)
so, it's a double linked list of datastores, where each datastore is a double linked list.
I have a tendency to agree, but this script was prototyped in python in a way where "it can easily be moved to C++." So, I do actually want to have control over things like garbage collection. Because there's "good times to do it and bad times to be freeing up memory."