Python:内存管理优化不一致?

Python:内存管理优化不一致?,python,python-2.7,memory-management,python-3.x,Python,Python 2.7,Memory Management,Python 3.x,我对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,

我对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)[GCC]在linux上

除了命令行和程序之间的输出差异外,这种优化的原因是什么?我认为如果我们考虑程序员应该直接管理的特殊情况,假设程序平均能节省10%以上的内存,这是相当乐观的。
这种行为是否有助于有效地最小化内存碎片

这里的区别只是其中一些对象是可变的,而另一些是不可变的

优化例如字符串文本的赋值是非常安全的,因为对同一个不可变对象的两个引用不会引起任何问题。由于您无法在适当的位置更改对象,因此任何更改都将意味着一个新对象,与旧对象分离

但是,对于列表等可变类型,如果设置
a=b
,则可能会遇到麻烦。可变对象可以就地更改,因此在列表示例中,附加到
a
的任何内容都将以
b
结束,反之亦然

解释器中的行为是不同的(小整数除外,它们是“内部的”),因为这些优化没有执行:

>>> a = "a b"
>>> b = "a b"
>>> a is b
False

另请参见:,关于字符串。您可能希望在帖子中添加一个示例,说明如果您使用
a=sys.intern('ab');b=sys.intern('ab')
Now
a is b
为插入的字符串返回True。