Python引用计数
Python 引用计数
Generational garbage collection is a technique based on the observation that most (80%+) objects are destroyed shortly after being created.
CPython’s GC uses three generations that have thresholds to trigger their collections. The youngest generation (0) has a high threshold to avoid the collection loop being run too frequently. If an object survives the GC, it will move to the second generation, and then the third.
In the collection function, a single generation is targeted, and it merges younger generations into it before execution. For this reason, if you run collect() on generation 1, it will collect generation 0. Likewise, running collect on generation 2 will collect() generations 0 and 1.
Every instance of PyObject has a property ob_refcnt. This property is a counter of the number of references to that object.
References to an object are incremented under many scenarios. In the CPython code base, there are over 3000 calls to Py_INCREF(). The most frequent calls are when an object is:
• assigned to a variable name • referenced as a function or method argument • returned,or yielded from a function
Can the garbage collector handle cycles that include del methods?
This is true in cpython beginning with version 3.4 (PEP 442).
_GC_CYCLE_FINALIZERS = (platform.python_implementation() == ‘CPython’ and sys.version_info >= (3, 4)) —–
The tracemalloc in the standard library can be used to debug memory allocation through the Object Allocator. It provides information on where an object was allocated, and the number of memory blocks allocated.
As a debug tool, it is beneficial to calculate the amount of memory consumed by running your code or detect memory leaks.
To enable memory tracing, you should start Python with the -X tracemalloc=1, where 1 is the number of frames deep you want to trace. Alternatively, you can enable memory tracing using the PYTHONTRACEMALLOC=1 environment variable. 1 is the number of frames deep you want to trace and can be replaced with any integer.
You can use the take_snapshot() function to create a snapshot instance, then compare multiple snapshots using compare_to().