Technology Sharing: How does Python perform memory management?

  Python mainly uses reference counting and memory pool mechanism for memory management. Next, Xiaoqian talks about these two methods in detail.

83.jpg

  1. Reference counting mechanism

  Python internally uses reference counting (recording how many references the object has) to keep track of objects in memory. When an object is created, the reference count of the object is incremented by 1; when the object is destroyed, the reference count of the object becomes 0. It will be recycled as garbage.

  The reference count increases:

  (1) The object is created, such as x=4.

  (2) Assign values ​​to other variables, such as y=x.

  (3) is passed to the function as a parameter, such as foo(x).

  (4) As an element of the container object, such as a=[1,x,'33'].

  Reference count reduction:

  (1) The reference of the object leaves its scope. For example, when the foo(x) function ends, the reference count of the object referenced by x is reduced by one.

  (2) The reference of the object is explicitly destroyed, such as del x or del y.

  (3) The alias of the object is assigned to other objects, x=789.

  (4) The object is removed from the window object, a.remove(x).

  Garbage collection:

  (1) The garbage collector will reclaim objects with a reference count of 0 and clear the memory space occupied by these objects.

  (2) When two objects refer to each other, if they are not held by other references, they will be recycled by the garbage collector.

  (3) The garbage collection mechanism also has a circular garbage collector, which can ensure the release of circular reference objects (a refers to b, b refers to a).

  Second, the memory pool mechanism

  In Python, many times the requested memory is a small block of memory. These small blocks of memory will be released shortly after the application. This means that the program will perform a large number of application and release operations during the runtime, which affects the execution efficiency of Python. . In order to speed up the execution efficiency of Python, Python introduced a memory pool mechanism to manage the application and release of small blocks of memory.

  All objects smaller than 256 bytes in Python use the memory pool allocator. In addition, some Python objects, such as integers, floating-point numbers, or lists, have independent memory pools, and these independent memory pools are not shared between objects. In other words, if a large number of integers are allocated and released, the memory pool used to cache these integers will no longer be allocated to floating-point numbers.

This article is from Qianfeng Education , please indicate the source for reprinting.

Guess you like

Origin blog.51cto.com/15128702/2676985