【python】创建大量实例,关闭动态绑定节省内存__slots__

class Player1:
    def __init__(self, uid, name, level):
        self.uid = uid
        self.name = name
        self.level = level

class Player2:
    __slots__ = ['uid', 'name', 'level']                #关闭动态绑定属性
    def __init__(self, uid, name, level):
        self.uid = uid
        self.name = name
        self.level = level

import tracemalloc
tracemalloc.start()
# start 
#la = [Player1(1,2,3) for _ in range(100000)]
lb = [Player2(1,2,3) for _ in range(100000)]
# end
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('filename')
for stat in top_stats[:10]: print(stat)

====================================================
la
C:/DLLM/t5.py:0: size=16.8 MiB, count=299993, average=59 B
C:\Python36\lib\tracemalloc.py:0: size=64 B, count=1, average=64 B

lb
C:/DLLM/t5.py:0: size=7056 KiB, count=100003, average=72 B
C:\Python36\lib\tracemalloc.py:0: size=64 B, count=1, average=64 B

你可能感兴趣的:(【python】创建大量实例,关闭动态绑定节省内存__slots__)