来自 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]
范围并没有什么神奇之处。少数负数可能包含在常见错误代码和列表负索引的范围内,并且上限只是设置为一个很好的二的幂。
来自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). */
关于python - 为什么 CPython 预分配一些整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57296092/