python - 为什么 CPython 预分配一些整数?

标签 python performance caching allocation cpython

来自 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/

相关文章:

python - "Least Astonishment"和可变默认参数

python - PyQt5/PySide2 广告拦截

c# - 将缓存与 AutomationElements 一起使用不会给我加速 - 预期或错误的用法?

macos - Mac : There was an error while executing `VBoxManage` , Vagrant 使用的 CLI

c# - 从Azure Redis缓存插入或删除值时,是否需要在代码级别进行同步?

python - 交叉多个 2D np 阵列以确定空间上连续的区域

java - 并行运行多个 "java -version"时 CPU 使用率过高

c# - 使用 System.Linq 占用多少空间?

session - 使用 ServiceStack 的多个 ICacheClient 实现

python - 如何使用 BeautifulSoup 从期刊版本列表中抓取 pdf 网址?