【问题标题】:Python: Memory Management Optimization Inconsistencies?Python:内存管理优化不一致?
【发布时间】: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 []

abid 返回值表明 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


【解决方案1】:

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

优化分配给例如字符串文字,因为对同一个不可变对象的两个引用不会导致任何问题。由于您无法就地更改对象,因此任何更改都将意味着一个新对象,与旧对象分开。

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

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

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

【讨论】:

  • 您可能希望将示例 sys.intern 添加到您的帖子中,以表明如果您使用 a=sys.intern('a b'); b=sys.intern('a b') 现在 a is b 将返回 True 用于实习字符串。
猜你喜欢
  • 1970-01-01
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多