我知道Python dict
將在物品被移除時「泄漏」(因爲物品的插槽將被魔術「已刪除」的值所覆蓋)...但set
類的行爲方式是否相同?保留一個set
是否安全,隨着時間的推移添加和刪除它的東西?Python:當物品被移除時,集合類是否「泄漏」,如字典?
編輯:好吧,我已經嘗試過了,這裏是我的發現:
>>> import gc >>> gc.collect() 0 >>> nums = range(1000000) >>> gc.collect() 0 ### rsize: 20 megs ### A baseline measurement >>> s = set(nums) >>> gc.collect() 0 ### rsize: 36 megs >>> for n in nums: s.remove(n) >>> gc.collect() 0 ### rsize: 36 megs ### Memory usage doesn't drop after removing every item from the set… >>> s = None >>> gc.collect() 0 ### rsize: 20 megs ### … but nulling the reference to the set *does* free the memory. >>> s = set(nums) >>> for n in nums: s.remove(n) >>> for n in nums: s.add(n) >>> gc.collect() 0 ### rsize: 36 megs ### Removing then re-adding keys uses a constant amount of memory… >>> for n in nums: s.remove(n) >>> for n in nums: s.add(n+1000000) >>> gc.collect() 0 ### rsize: 47 megs ### … but adding new keys uses more memory.
當你說Python字典會「泄漏」時,你能證實你的意思嗎?也許是對其他來源的引用? – 2010-02-28 04:13:40
AFAIK字典不會真正泄漏 - 例如(當你設置新的項目時)替換刪除值的假人是purget – 2010-02-28 04:15:46