How does python save memory for creating a large number of instances?
How does python save memory for creating a large number of instances? The details are as follows:
Case:
In an online game, a Player (id, name, status,...) is defined ,....), each online Player has an instance of Player in the server program. When there are many online players, a large number of instances (Millions of players) will be generated)
Requirements:
How can we reduce the memory overhead of these large instances?
How to do it?
First, you must understand that classes in python can dynamically add attributes. In fact, There Is A _ dict _ method in the memory to maintain this dynamic add attribute, which occupies the memory and closes it, does it meet the memory saving requirements?
#! /Usr/bin/python3 import timeimport 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', 'aliyun') print (player_1. _ dict _) print ('_' * 100) # dynamic assembly attribute player_1.money = 10000 player_1. _ dict _ ['time'] = time. time () print (player_1. _ dict _) print (player_1.money, player_1.time) print ('_' * 100) # print _ dict _ memory space occupied by print ('dict method occupies memory: ', sys. getsizeof (player_1. _ dict _) print ('_' * 100) # dynamically Delete the attribute print (player_1. _ dict _) del player_1. _ dict _ ['time'] del player_1.money print (player_1. _ dict __)
Declare the list of instance attribute names through the _ slots _ attribute
#! /Usr/bin/python3 class Player (object): # specify the class's Fixed Length attribute through the slots method _ 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', 'aliyun') print (player_1.id, player_1.name, player_1.status) # try to output the _ dict _ attribute. If no attribute is found, dynamic assembly class attributes cannot be obtained to save memory. try: print (player_1. _ dict _) failed t Exception as e: print (e)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.