Python内存管理机制

释放双眼,带上耳机,听听看~!

Python的内存管理机制:
引入计数、垃圾回收、内存池机制

一、引入计数

1、变量与对象


1
2
3
4
5
1In sum, variables are created when assigned, can reference any type of object, and must
2be assigned before they are referenced. This means that you never need to declare names
3used by your script, but you must initialize names before you can update them; counters,
4for example, must be initialized to zero before you can add to them.
5
  • 变量赋值的时候才创建,它可以指向(引用)任何类型的对象

  • python里每一个东西都是对象,它们的核心就是一个结构体:PyObject

  • 变量必须先赋值,再引用。

  • 比如,你定义一个计数器,你必须初始化成0,然后才能自增。

  • 每个对象都包含两个头部字段(类型标识符和引用计数器)

关系图如下:

Python内存管理机制

Names and objects after running the assignment a = 3. Variable a becomes a
reference to
the object 3. Internally, the variable is really a pointer to the object’s memory space created by running
the literal expression 3.


1
2
3
4
5
1These links from variables to objects are called references in Python—that is, a reference
2is a kind of association, implemented as a pointer in memory.1 Whenever the variables
3are later used (i.e., referenced), Python automatically follows the variable-to-object
4links. This is all simpler than the terminology may imply. In concrete terms:
5
  • Variables are

entries in a system table, with spaces for
links to objects.

  • Objects are pieces of allocated memory, with enough space to represent the values for which they stand.

  • References are automatically followed pointers from variables to objects.

  • objects have two header fields,

a type designator and
a reference counter.


1
2
3
4
5
6
7
1In Python, things work more simply.
2Names have no types; as stated earlier, types live with objects, not names. In the preceding
3listing, we’ve simply changed a to reference different objects. Because variables
4have no type, we haven’t actually changed the type of the variable a; we’ve simply made
5the variable reference a different type of object. In fact, again, all we can ever say about
6a variable in Python is that it references a particular object at a particular point in time.
7

变量名没有类型,
类型属于对象(因为变量引用对象,所以类型随对象)
在Python中,变量是
一种特定类型对象在
一个特定的时间点的引用。

2、共享引用


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1>>> a = 3
2>>> b = a
3>>>
4>>> id(a)
51747479616
6>>> id(b)
71747479616
8>>>
9>>> hex(id(a))
10'0x68286c40'
11>>> hex(id(b))
12'0x68286c40'
13>>>
14

Python内存管理机制


1
2
3
4
5
6
1This scenario in Python—with multiple names referencing the same object—is usually
2called a shared reference (and sometimes just a shared object). Note that the names a
3and b are not linked to each other directly when this happens; in fact, there is no way
4to ever link a variable to another variable in Python.
5Rather, both variables point to the same object via their references.
6

1、id() 是 python 的内置函数,用于返回对象的标识,即对象的内存地址。


1
2
3
4
5
6
7
8
9
1>>> help(id)
2Help on built-in function id in module builtins:
3
4id(obj, /)
5    Return the identity of an object.
6    
7    This is guaranteed to be unique among simultaneously existing objects.
8    (CPython uses the object's memory address.)
9

2、引用所指判断

通过is进行引用所指判断,is是用来判断两个引用所指的对象是否相同。

整数


1
2
3
4
5
6
7
8
9
10
1>>> a = 256
2>>> b = 256
3>>> a is b
4True
5>>> c = 257
6>>> d = 257
7>>> c is d
8False
9>>>
10

短字符串


1
2
3
4
5
6
1>>> e = "Explicit"
2>>> f = "Explicit"
3>>> e is f
4True
5>>>
6

长字符串


1
2
3
4
5
6
1>>> g = "Beautiful is better"
2>>> h = "Beautiful is better"
3>>> g is h
4False
5>>>
6

列表


1
2
3
4
5
6
1>>> lst1 = [1, 2, 3]
2>>> lst2 = [1, 2, 3]
3>>> lst1 is lst2
4False
5>>>
6

由运行结果可知:

1、Python
缓存
整数
短字符串,因此每个对象在内存中只存有一份,引用所指对象就是相同的,即使使用赋值

语句,也只是创造新的引用,而不是对象本身;

2、Python没有缓存长字符串、列表及其他对象,可以由多个相同的对象,可以使用赋值语句创建出新的对象。

原理:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
1# 两种优化机制: 代码块内的缓存机制, 小数据池。
2
3# 代码块
4代码全都是基于代码块去运行的(好比校长给一个班发布命令),一个文件就是一个代码块。
5不同的文件就是不同的代码块。
6
7# 代码块内的缓存机制
8Python在执行同一个代码块的初始化对象的命令时,会检查是否其值是否已经存在,如果存在,会将其重用。
9换句话说:执行同一个代码块时,遇到初始化对象的命令时,他会将初始化的这个变量与值存储在一个字典中,
10在遇到新的变量时,会先在字典中查询记录,
11如果有同样的记录那么它会重复使用这个字典中的之前的这个值。
12所以在文件执行时(同一个代码块)会把两个变量指向同一个对象,
13满足缓存机制则他们在内存中只存在一个,即:id相同。
14
15注意:
16# 机制只是在同一个代码块下!!!,才实行。
17# 满足此机制的数据类型:int str bool。
18
19
20# 小数据池(驻留机制,驻村机制,字符串的驻存机制,字符串的缓存机制等等)
21不同代码块之间的优化。
22# 适应的数据类型:str bool int
23int: -5 ~256
24str: 一定条件下的str满足小数据池。
25bool值 全部。
26
27
28# 总结:
29如果你在同一个代码块中,用同一个代码块中的缓存机制。
30如果你在不同代码块中,用小数据池。
31
32# 优点:
331,节省内存。
342,提升性能。
35

github上有详细的例子,wtfpython

3、查看对象的引用计数

在Python中,每个对象都有指向该对象的引用总数 —
引用计数

查看对象的引用计数:
sys.getrefcount()

当对变量重新赋值时,它原来引用的值去哪啦?比如下面的例子,给 s 重新赋值 字符串 apple,6 跑哪里去啦?


1
2
3
1>>> s = 6
2>>> s = 'apple'
3

答案是:当变量重新赋值时,它原来指向的对象(如果没有被其他变量或对象引用的话)的空间可能被收回(
垃圾回收


1
2
3
4
5
1The answer is that in Python, whenever a name is assigned to a new object, the space
2held by the prior object is reclaimed if it is not referenced by any other name or object.
3This automatic reclamation of objects’ space is known as garbage collection, and makes
4life much simpler for programmers of languages like Python that support it.
5

普通引用


1
2
3
4
5
6
7
8
9
10
11
12
1>>> import sys
2>>>
3>>> a = "simple"
4>>> sys.getrefcount(a)
52
6>>> b = a
7>>> sys.getrefcount(a)
83
9>>> sys.getrefcount(b)
103
11>>>
12

注意:当使用某个引用作为参数,传递给
**getrefcount()**时,参数实际上创建了一个临时的引用。因此,
**getrefcount()**所得到的结果,会比期望的
多1

三、垃圾回收

当Python中的对象越来越多,占据越来越大的内存,启动垃圾回收(
garbage collection),将没用的对象清除。

1、原理

当Python的某个对象的引用计数降为0时,说明没有任何引用指向该对象,该对象就成为要被回收的垃圾。

比如某个新建对象,被分配给某个引用,对象的引用计数变为1。如果引用被删除,对象的引用计数为0,那么该对象就可以被垃圾回收。


1
2
3
4
5
6
7
8
9
10
11
12
1Internally, Python accomplishes this feat by keeping a counter in every object that keeps
2track of the number of references currently pointing to that object. As soon as (and
3exactly when) this counter drops to zero, the object’s memory space is automatically
4reclaimed. In the preceding listing, we’re assuming that each time x is assigned to a new
5object, the prior object’s reference counter drops to zero, causing it to be reclaimed.
6
7The most immediately tangible benefit of garbage collection is that it means you can
8use objects liberally without ever needing to allocate or free up space in your script.
9Python will clean up unused space for you as your program runs. In practice, this
10eliminates a substantial amount of bookkeeping code required in lower-level languages
11such as C and C++.
12

2、解析del

del 可以使 对象的引用计数减 1,该表引用计数变为0,用户不可能通过任何方式接触或者动用这个对象,当垃圾回收启动时,Python扫描到这个引用计数为0的对象,就将它所占据的内存清空。

注意

1、垃圾回收时,Python不能进行其它的任务,频繁的垃圾回收将大大降低Python的工作效率;

2、Python只会在特定条件下,自动启动垃圾回收(垃圾对象少就没必要回收)

3、当Python运行时,会记录其中分配对象(
object allocation)和取消分配对象(
object deallocation)的次数。

当两者的差值高于某个阈值时,垃圾回收才会启动。


1
2
3
4
5
6
1>>> import gc
2>>>
3>>> gc.get_threshold() #gc模块中查看垃圾回收阈值的方法
4(700, 10, 10)
5>>>
6

阈值分析:

700 即是垃圾回收启动的阈值;

每10 次 0代 垃圾回收,会配合 1次 1代 的垃圾回收;而每10次1代的垃圾回收,才会有1次的2代垃圾回收;

当然也是可以手动启动垃圾回收:


1
2
3
4
5
1>>> gc.collect()       #手动启动垃圾回收
252
3>>> gc.set_threshold(666, 8, 9) # gc模块中设置垃圾回收阈值的方法
4>>>
5

何为分代回收

  • Python将所有的对象分为0,1,2三代;

  • 所有的新建对象都是0代对象;

  • 当某一代对象经历过垃圾回收,依然存活,就被归入下一代对象。


1
2
3
4
5
6
1分代技术是一种典型的以空间换时间的技术,这也正是java里的关键技术。这种思想简单点说就是:对象存在时间越长,越可能不是垃圾,应该越少去收集。
2这样的思想,可以减少标记-清除机制所带来的额外操作。分代就是将回收对象分成数个代,每个代就是一个链表(集合),代进行标记-清除的时间与代内对象
3存活时间成正比例关系。
4从上面代码可以看出python里一共有三代,每个代的threshold值表示该代最多容纳对象的个数。默认情况下,当0代超过700,或1,2代超过10,垃圾回收机制将触发。
50代触发将清理所有三代,1代触发会清理1,2代,2代触发后只会清理自己。
6

标记-清除

Python内存管理机制


1
2
3
4
5
1标记-清除机制,顾名思义,首先标记对象(垃圾检测),然后清除垃圾(垃圾回收)。
2首先初始所有对象标记为白色,并确定根节点对象(这些对象是不会被删除),标记它们为黑色(表示对象有效)。
3将有效对象引用的对象标记为灰色(表示对象可达,但它们所引用的对象还没检查),检查完灰色对象引用的对象后,将灰色标记为黑色。
4重复直到不存在灰色节点为止。最后白色结点都是需要清除的对象。
5

如何解决
循环引用
可能导致的内存泄露问题呢?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1More on Python Garbage Collection
2Technically speaking, Python’s garbage collection is based mainly upon reference counters,
3as described here; however, it also has a component that detects and reclaims
4objects with cyclic references in time. This component can be disabled if you’re sure
5that your code doesn’t create cycles, but it is enabled by default.
6 Circular references are a classic issue in reference count garbage collectors. Because
7references are implemented as pointers, it’s possible for an object to reference itself, or
8reference another object that does. For example, exercise 3 at the end of Part I and its
9solution in Appendix D show how to create a cycle easily by embedding a reference to
10a list within itself (e.g., L.append(L)). The same phenomenon can occur for assignments
11to attributes of objects created from user-defined classes. Though relatively rare, because
12the reference counts for such objects never drop to zero, they must be treated
13specially.
14For more details on Python’s cycle detector, see the documentation for the gc module
15in Python’s library manual. The best news here is that garbage-collection-based memory
16management is implemented for you in Python, by people highly skilled at the task.
17

答案是:

  1. **弱引用   使用

weakref 模块下的
ref 方法**

  1. 强制把其中一个引用变成 None


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
1import gc
2import objgraph
3import sys
4import weakref
5
6
7def quote_demo():
8    class Person:
9        pass
10
11    p = Person()  # 1
12    print(sys.getrefcount(p))  # 2  first
13
14    def log(obj):
15        # 4  second 函数执行才计数,执行完释放
16        print(sys.getrefcount(obj))
17
18    log(p)  # 3
19
20    p2 = p  # 2
21    print(sys.getrefcount(p))  # 3
22    del p2
23    print(sys.getrefcount(p))  # 3 - 1 = 2
24
25
26def circle_quote():
27    # 循环引用
28    class Dog:
29        pass
30
31    class Person:
32        pass
33
34    p = Person()
35    d = Dog()
36
37    print(objgraph.count("Person"))
38    print(objgraph.count("Dog"))
39
40    p.pet = d
41    d.master = p
42
43    # 删除 p, d之后, 对应的对象是否被释放掉
44    del p
45    del d
46
47    print(objgraph.count("Person"))
48    print(objgraph.count("Dog"))
49
50
51def solve_cirecle_quote():
52    # 1. 定义了两个类
53    class Person:
54        def __del__(self):
55            print("Person对象, 被释放了")
56
57        pass
58
59    class Dog:
60        def __del__(self):
61            print("Dog对象, 被释放了")
62
63        pass
64
65    p = Person()
66    d = Dog()
67
68    p.pet = d
69    d.master = p
70
71    p.pet = None  # 强制置 None
72    del p
73    del d
74
75    gc.collect()
76
77    print(objgraph.count("Person"))
78    print(objgraph.count("Dog"))
79
80
81def sovle_circle_quote_with_weak_ref():
82    # 1. 定义了两个类
83    class Person:
84        def __del__(self):
85            print("Person对象, 被释放了")
86
87        pass
88
89    class Dog:
90        def __del__(self):
91            print("Dog对象, 被释放了")
92
93        pass
94
95    p = Person()
96    d = Dog()
97
98    p.pet = d
99    d.master = weakref.ref(p)
100
101    del p
102    del d
103
104    gc.collect()
105
106    print(objgraph.count("Person"))
107    print(objgraph.count("Dog"))
108
109
110if __name__ == "__main__":
111    quote_demo()
112    circle_quote()
113    solve_cirecle_quote()
114    sovle_circle_quote_with_weak_ref()
115

四、内存池机制

Python中有分为大内存和小内存:(256K为界限分大小内存)

  1. 大内存使用malloc进行分配
  2. 小内存使用内存池进行分配
  3. Python的内存池(金字塔)

Python内存管理机制

第+3层:最上层,用户对Python对象的直接操作

第+1层和第+2层:内存池,有Python的接口函数PyMem_Malloc实现

    • 若请求分配的内存在1~256字节之间就使用内存池管理系统进行分配,调用malloc函数分配内存,
      • 但是每次只会分配一块大小为256K的大块内存,不会调用free函数释放内存,将该内存块留在内存池中以便下次使用

第0层:大内存  —–> 若请求分配的内存大于256K,malloc函数分配内存,free函数释放内存。

第-1,-2层:操作系统进行操作

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++ explicit关键字

2022-1-11 12:36:11

安全经验

Spring Security 4.1.3 发布,Spring 安全框架

2016-8-24 11:12:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索