【发布时间】:2019-01-14 21:08:17
【问题描述】:
在 Python 2 中,一个空字符串正好占用 37 个字节,
>>>> print sys.getsizeof('')
37
在 Python 3.6 中,相同的调用会输出 49 个字节,
>>>> print(sys.getsizeof(''))
49
现在我认为这是因为 在 Python 3 中,所有字符串现在都是 Unicode。但是,令我惊讶的是,这里有一些令人困惑的输出,
Python 2.7
>>>> print sys.getsizeof(u'')
52
>>>> print sys.getsizeof(u'1')
56
Python 3.6
>>>>print(sys.getsizeof(''))
49
>>>>print(sys.getsizeof('1'))
50
- 空字符串的大小不同。
- 在 Python 2 中添加一个字符时需要 4 个额外的字节,而在 Python 3 中只需要一个字节
为什么两个版本的内存占用不同?
编辑
我指定了我的 python 环境的确切版本,因为不同的 Python 3 版本之间存在差异。
【问题讨论】:
标签: python python-3.x python-2.7 memory unicode