python基础之小数据池

关于池的概念,大家也许知道 连接池,代理池。然而现在我们提到的小数据池,则是一些Int和string已经创建好的并放在池子里等着我们去调用的对象。

'''对于整数,Python官方文档中这么说:
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.

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

string: 

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

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

  3.用乘法得到的字符串

    1)乘数为1时:

      仅含大小写字母,数字,下划线,默认驻留。

      含其他字符,长度<=1,默认驻留。

      含其他字符,长度>1,默认驻留。

    2)乘数>=2时:

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

  4.指定驻留。

    需要调用sys模块中的intern方法

    from sys import intern

    a = intern('hello'*20)

    b = intern('hello'*20)

    print(a is b) # True

简单的总结一下 如果查看两个变量,并且这两个变量属于小数据池的范畴,则他们的id相同

原文地址:https://www.cnblogs.com/wuxiaoshi/p/9737377.html