gc.collect() 函数到底做了什么?

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

我无法理解 python 函数 gc.collect() 的确切功能。 该函数是否仅收集那些可收集的对象,以便在达到 gc.threshold 后稍后释放 space?还是 gc.collect() 收集对象并自动摆脱它收集的任何东西,以便 space 可以在执行代码后立即释放?

视情况而定!如果不带参数或使用 generation=2 作为参数调用,它将释放可收集的对象。如果使用 generation=1 调用,它不会清除空闲列表。

来自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.