Python中的小数据池

小数据池

1 对于整数,Python官方文档中这么说:
2 The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined.
3 
4 对于字符串:
5 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 string is created or interned. The distinct values are stored ina string intern pool.

Python自动将-5~256的整数进行了缓存,当你将这些整数赋值给变量时,并不会重新创建对象,而是使用已经创建好的缓存对象。

python会将一定规则的字符串在字符串驻留池中,创建一份,当你将这些字符串赋值给变量时,并不会重新创建对象, 而是使用在字符串驻留池中创建好的对象。

  其实,无论是缓存还是字符串驻留池,都是python做的一个优化,就是将~5-256的整数,和一定规则的字符串,放在一个‘池’(容器,或者字典)中,无论程序中那些变量指向这些范围内的整数或者字符串,那么他直接在这个‘池’中引用,言外之意,就是内存中之创建一个。

适用对象 int(float),str,bool 

对象的具体细则:(了解即可)

int:那么大家都知道对于整数来说,小数据池的范围是-5~256 ,如果多个变量都是指向同一个(在这个范围内的)数字,他们在内存中指向的都是一个内存地址。

字符串的驻留规定

str:字符串要从下面这几个大方向讨论:

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

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

bool值就是True,False,无论你创建多少个变量指向True,False,那么他在内存中只存在一个。

看一下用了小数据池(驻留机制)的效率有多高:

显而易见,节省大量内存在字符串比较时,非驻留比较效率o(n),驻留时比较效率o(1)。

猜你喜欢

转载自www.cnblogs.com/shiqi17/p/12723322.html
今日推荐