为什么 CPython 会预先分配一些整数?

Why CPython pre-allocates some integer numbers?

CPython 文档 here 指出:

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.

这使得这个比较成立:

>>> a = -3
>>> b = -3
>>> a is b
True

我想知道这背后的原因是什么,为什么有些号码是预先分配的,为什么要特别分配这些号码?

因为 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).
*/