【问题标题】:Why CPython pre-allocates some integer numbers?为什么 CPython 会预先分配一些整数?
【发布时间】:2019-12-09 06:54:37
【问题描述】:
来自 CPython 文档 here,声明如下:
当前的实现为 -5 到 256 之间的所有整数保留一个整数对象数组,当您在该范围内创建一个 int 时,实际上您只是获取对现有对象的引用。
这使得这个比较成立:
>>> a = -3
>>> b = -3
>>> a is b
True
我想知道这背后的原因是什么,为什么要预先分配一些数字以及为什么要特别分配这些数字?
【问题讨论】:
标签:
python
performance
caching
allocation
cpython
【解决方案1】:
因为 CPython 的实现者已经决定,出于性能原因,这是一个很好的预分配范围,因为它涵盖了最常用的整数值。 [-5,256] 的范围没有什么神奇之处。少数负数可能包含在常见错误代码和列表负索引的范围内,并且上限只是设置为 2 的整数幂。
来自CPython source code的评论:
/* Small integers are preallocated in this array so that they
can be shared.
The integers that are preallocated are those in the range
-NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
*/