我對內存中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 []
的id
爲a
和b
返回值表明is
運營工作正常,但「內存佔用優化」算法似乎是不一致的工作。
最後兩個print
輸出和python命令行解釋器行爲揭示了一些實現錯誤還是Python應該這樣做?
我在OpenSUSE 13.1環境中運行了這些測試。與Python 2.7.6和Python 3.3.5(默認, 2014年3月27日,17:16:46)[GCC]在Linux上。
除了命令行和程序之間的輸出差異之外,這種優化的原因是什麼?我認爲假設程序平均可以節省10%以上的內存是相當樂觀的,除非我們考慮應由程序員直接管理的特殊情況。
此行爲是否有助於有效減少內存碎片?
參見:http://stackoverflow.com/ q/15541404/3001761,http://stackoverflow.com/q/21203212/3001761關於字符串具體。 – jonrsharpe