2014-06-24 36 views
1

我對內存中Python對象的分配感到困惑。看起來,預定義類型的分配並不一致。這是我在這個問題上cogitations的產品: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 [] 

idab返回值表明is運營工作正常,但「內存佔用優化」算法似乎是不一致的工作。

最後兩個print輸出和python命令行解釋器行爲揭示了一些實現錯誤還是Python應該這樣做?

我在OpenSUSE 13.1環境中運行了這些測試。與Python 2.7.6和Python 3.3.5(默認, 2014年3月27日,17:16:46)[GCC]在Linux上。

除了命令行和程序之間的輸出差異之外,這種優化的原因是什麼?我認爲假設程序平均可以節省10%以上的內存是相當樂觀的,除非我們考慮應由程序員直接管理的特殊情況。

此行爲是否有助於有效減少內存碎片?

+0

參見:http://stackoverflow.com/ q/15541404/3001761,http://stackoverflow.com/q/21203212/3001761關於字符串具體。 – jonrsharpe

回答

2

這裏的區別只是這些對象中的一些是可變的,而且是一些不可變的。

這是完全安全的,以優化分配到例如字符串文字,因爲對同一個不可變對象的兩個引用不會導致任何問題。由於您無法就地更改對象,所以任何更改都將意味着一個新對象,與舊對象分開。

但是,如果使用列表這樣的可變類型,如果您設置了a = b,則最終可能會遇到麻煩。可變對象可以在原地進行更改,因此在您的列表示例中,您添加到a的任何內容都將以b結尾,反之亦然。

在解釋器的行爲是不同的(除了小整數,這是「實習」),因爲這些最佳化不被執行:

>>> a = "a b" 
>>> b = "a b" 
>>> a is b 
False 
+1

如果您使用'a = sys,您可能希望添加示例[sys.intern](https://docs.python.org/3.0/library/sys.html#sys.intern)以顯示該示例。實習生('a b'); b = sys.intern('a b')'現在'a是b'對於實參字符串返回True。 – dawg