Python introduces a mechanism: reference counting.
Python uses reference counting internally to keep track of objects in memory. Python keeps an internal record of how many references an object has. That’s the reference count.
To summarize, objects increase the reference count by one in the following cases:
1. The object is created: x=4
2. Someone else is created: y=x
3. Passed as an argument to function foo(x)
As an element of a container object: a=[1,x,’33’]
Reference count reduction
1. A local reference is out of scope. For example, the foo(x) function above ends with the object reference to which x points minus 1.
2. The alias of the object is explicitly destroyed: del x; Or del y
3. An alias of the object is assigned to another object: x=789
4. Object removed from a window object: mylist.remove (x)
5. The window object itself is destroyed: del myList, or the window object itself is out of scope.
The garbage collection
1. When there are unused parts of memory, the garbage collector cleans them up. It checks for objects that have a reference count of zero and then clears them out of memory. Of course, in addition to the zero reference count being cleared, there is another case that can be cleared by the garbage collector: when two objects refer to each other, their other references are already zero.
2. The garbage collection mechanism also has a cyclic garbage collector that ensures that cyclic reference objects (a refers to B, and B refers to A, so that its reference count is never zero) are released.
In Python, many times the memory that is requested is small chunks of memory that are quickly freed. Since the memory is not allocated to create objects, there is no object-level memory pooling mechanism. This means that Python performs a lot of malloc and free operations at runtime, switching between user and core state frequently, which severely affects Python execution efficiency. To speed up Python’s execution, Python introduced a memory pool mechanism to manage the allocation and release of small chunks of memory.
Memory pool mechanism
Python provides a garbage collection mechanism for memory, but it puts unused memory into the memory pool rather than returning it to the operating system.
All objects smaller than 256 bytes in Python use pymalloc’s allocator, while large objects use the system’s Malloc. In addition, Python objects such as integers, floating-point numbers, and lists have their own private memory pools. Objects do not share their memory pools. That is, if you allocate and free a large number of integers, the memory used to cache them can no longer be allocated to floating point numbers.