Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does the gc.collect() function do?

I am having trouble understanding what exactly the python function gc.collect() does. Does the function only collects those objects that are collectable, to free up the space at a later time once the gc.threshold is reached? or does gc.collect() collect objects and also automatically get rid of whatever it collected, so that the space can be freed immediately after executing the code?

like image 764
chico0913 Avatar asked Oct 27 '22 03:10

chico0913


1 Answers

It depends! If called with no argument or with generation=2 as an argument, it would free the objects that are collectable. If called with generation=1 it would not clear the free lists.

From the documentation:

With no arguments, run a full collection. The optional argument generation may be an integer specifying which generation to collect (from 0 to 2). A ValueError is raised if the generation number is invalid. The number of unreachable objects found is returned.

The free lists maintained for a number of built-in types are cleared whenever a full collection or collection of the highest generation (2) is run. Not all items in some free lists may be freed due to the particular implementation, in particular float.

like image 127
Jacques Gaudin Avatar answered Nov 15 '22 07:11

Jacques Gaudin