python_如何为创建大量实例节省内存?

时间:2023-12-21 20:50:02

案例:

  某网络游戏中,定义了玩家类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)