【发布时间】:2014-08-15 07:49:35
【问题描述】:
我对 Python 对象在内存中的分配感到很困惑。预定义类型的分配似乎并不一致。这是我对这个问题的思考的产物:
a = None
b = None
print( a, b is a) # it outputs True, one single instance of None
a = 'a'
b = 'a'
print( a, b is a) # it outputs True, one single instance of a string
a = 2
b = 2
print( a, b is a) # it outputs True, one single instance of an int
a = 2.5
b = 2.5
print( a, b is a) # it outputs True, one single instance of a float
# from the python command line 'b is a' returns False
a = 'a b'
b = 'a b'
print( a, b is a) # it outputs True, one single instances of the same string
# from the python command line 'b is a' returns False
a = ()
b = ()
print( a, b is a) # it outputs True, one single instance of a ()
a = {}
b = {}
print( a, b is a) # it outputs False, two different instances of the same empty {}
a = []
b = []
print( a, b is a) # it outputs False, two different instances of the same []
a 和 b 的 id 返回值表明 is 运算符工作正常,但“内存使用优化”算法似乎工作不一致。
最后两个 print 输出和 python 命令行解释器行为是否揭示了一些实现错误,或者 Python 应该以这种方式运行?
我在 OpenSUSE 13.1 环境中运行了这些测试。使用 Python 2.7.6 和 Python 3.3.5(默认, 2014 年 3 月 27 日,17:16:46)Linux 上的 [GCC]。
除了命令行和程序的输出差异之外,这种优化的原因是什么?我认为假设程序平均节省 10% 以上的内存是相当乐观的,除非我们考虑应该由程序员直接管理的特殊情况。
这种行为是否有助于有效地减少内存碎片?
【问题讨论】:
标签: python python-2.7 memory-management python-3.x