Loading

Python 缓存

官方文档

A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is ablock. A script file (a file given as standard input to the interpreter or specified as a command line argument to theinterpreter) is a code block. A script command (a command specified on the interpreter command line with the ‘-c‘ option) is a code block. The string argument passed to the built-in functions eval() and exec() is a code block.A code block is executed in an execution frame. A frame contains some administrative information (used for debugging)and determines where and how execution continues after the code block’s execution has completed.

意思是说

Python程序是由代码块构造的。块是一个python程序的文本,他是作为一个单元执行的。代码块:一个模块,一个函数,一个类,一个文件等都是一个代码块。而作为交互方式输入的每个命令都是一个代码块。对于每个def function()都是一个单独的代码块

代码块的缓存机制

Python在执行同一个代码块的初始化对象的命令时,会检查是否其值经存在,如果存在,会将其重用。换句话说:执行同一个代码块时,遇到初始化对象的命令时,他会将初始化的这个变量与值存储在一个字典中,在遇到新的变量时,会先在字典中查询记录,如果有同样的记录那么它会重复使用这个字典中的之前的这个值。所以在给出的例子中,文件执行时(同一个代码块)会把i1、i2两个变量指向同一个对象,满足缓存机制则他们在内存中只存在一个,最直接的表现就是:id相同。

代码块的缓存机制的好处

能够提高一些字符串,整数处理人物在时间和空间上的性能;需要值相同的字符串,整数的时候,直接从‘字典’中取出复用,避免频繁的
创建和销毁,提升效率,节约内存。

小数据池

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in thatrange you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspectthe behaviour of Python in this case is undefined.Incomputer science, string interning is a method of storing only onecopy of each distinct string value, which must be immutable.Interning strings makes some stringprocessing tasks more time- or space-efficient at the cost of requiring moretime when the stringis created or interned. The distinct values are stored ina string intern pool.

意思是说

Python自动将-5~256的整数进行了缓存,当你将这些整数赋值给变量时,并不会重新创建对象,而是使用已经创建好的缓存对象。python会将一定规则的字符串在字符串驻留池中,创建一份,当你将这些字符串赋值给变量时,并不会重新创建对象, 而是使用在字符串驻留池中创建好的对象。
其实,无论是缓存还是字符串驻留池,都是python做的一个优化,就是将~5-256的整数,和一定规则的字符串,放在一个‘池’(容器,或者字典)中,无论程序中那些变量指向这些范围内的整数或者字符串,那么他直接在这个‘池’中引用,言外之意,就是内存中之创建一个。

这样做的好处是:
能够提高一些字符串,整数处理人物在时间和空间上的性能;需要值相同的字符串,整数的时候,直接从‘池’里拿来用,避免频繁的创建和销毁,提升效率,节约内存。

对于int

小数据池的范围是-5~256 ,如果多个变量都是指向同一个(在这个范围内的)数字,他们在内存中指向的都是一个内存地址。

对于str

1 字符串的长度为0或者1,默认都采用了驻留机制(小数据池)。

2 字符串的长度>1,且只含有大小写字母,数字,下划线时,才会默认驻留。

3 用乘法得到的字符串:

乘数为1时:仅含大小写字母,数字,下划线,默认驻留。含其他字符,长度<=1,默认驻留。含其他字符,长度>1,默认驻留。

乘数>=2时:仅含大小写字母,数字,下划线,总长度<=20,默认驻留。

对于bool

无非是Ture / False 无论你创建多少个变量指向True,False,那么他在内存中只存在一个, None 更是全局唯一的对象。

可以自由的制定在缓存中驻留的资源

from sys import intern
a = intern('monkey@'*100)
b = intern('monkey@'*100)
print(a is b)

指定驻留是你可以指定任意的字符串加入到小数据池中,让其只在内存中创建一个对象,多个变量都是指向这一个字符串。

posted @ 2020-06-18 17:37  StKali  阅读(655)  评论(0编辑  收藏  举报