在python中,爲了優化速度,避免頻繁申請和銷燬內存空間,python使用小整數池來緩存 range(-5,257) 之間的整數(這裏不包含257),這些小整數在賦值引用時使用的都是同一個對象和內存地址。python
>>> 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優化