1. 程式人生 > >python_如何為創建大量實例節省內存?

python_如何為創建大量實例節省內存?

pri object 大量 sizeof time gets __init__ 屬性 __slots__

案例:

  某網絡遊戲中,定義了玩家類Player(id, name, status,....),每有一個在線玩家,在服務器程序內有一個Player的實例,當在線人數很多時,將產生大量實例(百萬級別)

  需求:

  如何降低這些大量實例的內存開銷?

如何做?

首先要明白,python中的類可以動態的添加屬性,實則在內存中有個__dict__方法維護了這種動態添加屬性,它占有內存,把它關掉,不就達到省內存要求了?

#!/usr/bin/python3

import time
import sys


class Player(object):
    def __init__(self, id, name, status):
        self.id = id
        self.name = name
        self.status = status

if __name__ == ‘__main__‘:
    player_1 = Player(1, ‘bei_bei‘, ‘上線‘)
    print(player_1.__dict__)
    
    print(‘_‘ * 100)
    # 動態裝配屬性
    player_1.money = 10000
    player_1.__dict__[‘time‘] = time.time()
    print(player_1.__dict__)
    print(player_1.money, player_1.time)
    
    print(‘_‘ * 100)
    # 打印__dict__占用的內存空間
    print(‘dict方法占用內存:‘, sys.getsizeof(player_1.__dict__))
    
    print(‘_‘*100)
    # 動態刪除屬性
    print(player_1.__dict__)
    del player_1.__dict__[‘time‘]
    
    del player_1.money
    print(player_1.__dict__)

通過__slots__屬性,聲明實例屬性名字的列表

#!/usr/bin/python3


class Player(object):
    # 通過slots方法指定類的定長屬性
    __slots__ = [‘id‘, ‘name‘, ‘status‘]
    
    def __init__(self, id, name, status):
        self.id = id
        self.name = name
        self.status = status


if __name__ == ‘__main__‘:
    player_1 = Player(1, ‘bei_bei‘, ‘上線‘)
    print(player_1.id, player_1.name, player_1.status)
    
    # 嘗試輸出__dict__屬性,發現沒有,就無法動態的裝配類屬性,達到省內存的目的
    try:
        print(player_1.__dict__)
    except Exception as e:
        print(e)

  

  

python_如何為創建大量實例節省內存?