Python memory management and python Memory Management
1. in Python, integers and short characters are cached by Python for reuse. When we create multiple references equal to 1, all these references are actually directed to the same object.
a = 1b = 1print hex(id(a))print hex(id(b))0x1e6e038L0x1e6e038L
Id () to obtain the memory address
2. Object Reference
From sys import getrefcounta = [1, 2, 3] B = aprint (getrefcount (B) a = 1 print (getrefcount (B ))
Getrefcount can obtain the number of times this object is referenced. Note that when a reference is passed to getrefcount () as a parameter, the parameter actually creates a temporary reference. Therefore, the getrefcount () result is 1 more than expected.
3. Garbage collection and reduced counting
If the number of referenced objects is 0, the object will be recycled.
During garbage collection, Python cannot perform other tasks. Frequent garbage collection will greatly reduce the efficiency of Python. If there are not many objects in the memory, there is no need to start garbage collection. Therefore, Python only automatically starts garbage collection under certain conditions. When Python is running, the number of times of object allocation and object deallocation is recorded. Garbage collection starts only when the difference between the two is higher than a threshold value.
We can view the threshold value through the get_threshold () method of the gc module:
import gcprint(gc.get_threshold())
Return Value (700, 10, 10). The next two 10 values are the threshold values related to generation recovery, which can be seen later. 700 is the threshold for starting garbage collection. You can use the set_threshold () method in gc to reset it. You can also manually start garbage collection by Using gc. collect ().
4. Generational recovery
Python also adopts the generation recycling policy. The basic assumption of this policy is that objects that have been alive for a longer period of time cannot become garbage in subsequent programs. Our programs often produce a large number of objects, many objects are generated and disappear quickly, but some objects are used for a long time. Out of trust and efficiency, we believe in their usefulness for such "long-lived" objects, So we reduce the frequency of scanning them in garbage collection.
Python divides all objects into three generations: 0, 1 and 2. All new objects are generation 0 objects. When a generation of objects is still alive after garbage collection, they are classified as the next generation objects. When garbage collection is started, all the 0-generation objects will be scanned. If the 0th generation passes through garbage collection for a certain number of times, scanning for 0th generation and 1st generation will be started. When the first generation has also undergone a certain amount of garbage collection, it will start scanning 0, 1, 2, that is, all objects.
Import gcgc. set_threshold (700, 10, 5)
You can manually set