在python中,为了优化速度,避免频繁申请和销毁内存空间,python使用小整数池来缓存 range(-5,257) 之间的整数(这里不包含257),这些小整数在赋值引用时使用的都是同一个对象和内存地址。
>>> print(id(-6), id(-5), id(256), id(257))
4395081424 4305320256 4305328608 4395080176
>>> print(id(-6), id(-5), id(256), id(257))
4397424720 4305320256 4305328608 4395080720
>>> print(id(-6), id(-5), id(256), id(257))
4397424880 4305320256 4305328608 4395081424
a = -5
b = -5
print(a is b)
# True
a = 1000
b = 1000
print(a is b)
False
与此类似,对于字符串,python中有一个intern机制,用来优化常用字符串对象的内存分配。长度不大于20而且不包含特殊字符的字符串在引用时指向同一个对象和内存地址。
>>> a = 'abc'
>>> b = 'abc'
>>> a is b
True
>>> a = 'a'*20
>>> b = 'a'*20
>>> a is b
True
>>> b = 'a'*21
>>> a = 'a'*21
>>> a is b
False
>>> a = 'hello world'
>>> b = 'hello world'
>>> a is b
False
>>> b = 'hello2world'
>>> a = 'hello2world'
>>> a is b
True
参考:
http://liuzhijun.iteye.com/blog/2263296
https://blog.csdn.net/wangyunfeis/article/details/77607156