Python对象分配地址

Python object allocation address

所以我在 Python 2.7 中遇到了一个有趣的行为,我很想知道为什么会这样。我在python 2.7中定义了以下4个数据结构:

在 python 中创建它们:

st = set(['apple', 'orange', 'apple', 'pear', 'orange', 'banana']) 
lst = [1, 2, 3, "4"] 
tpl = (1, 2, 3, '4') 
dct = {'one': 1, 'two': 2, 'three': 3};

这是 4 个对象的表示:

st.__repr__
<method-wrapper '__repr__' of set object at 0x7f234997ba48>

tpl.__repr__
<method-wrapper '__repr__' of tuple object at 0x7f23499667e0>

lst.__repr__
<method-wrapper '__repr__' of list object at 0x7f2349910b48>

dct.__repr__
<method-wrapper '__repr__' of dict object at 0x25af3a0>

如您所见,我的词典与其他词典 (0x7f23499*****) 相比,位于完全不同的内存部分 (0x25af3a0)。

我的问题是,为什么字典对象被放置到完全不同的内存部分?

Python 版本为 2.7.3(在 linux 上使用 GCC 4.7.2 编译),linux 版本为 3.18.0-kali3-amd64 #1 SMP Debian 3.18。 6-1~kali2 (2015-03-02) x86_64 GNU/Linux).

Python 使用 很多 微小的临时对象(尤其是 dicts,用于传递参数、存储属性等)。为了减少每次创建或销毁此类对象时分配和释放内存的开销,CPython 通过为各种大小的小对象预分配内存槽数组进行优化。

因此,当您创建一个小对象时,Python 不会按照您期望的方式分配内存。而是使用它自己的启发式算法 select 它已经预留的内存位置之一。只有当 Python 的 "arena" 预分配小块的相关部分已满时,才会分配新内存。