SoFunction
Updated on 2024-11-13

How python saves memory for creating lots of instances

How python saves memory for creating a large number of instances is as follows

Case in point:

In an online game, the player class Player(id, name, status,....) is defined. For every online player, there is an instance of Player within the server program, and when there are a lot of online players, a lot of instances (millions) will be created.

Demand:

How can we reduce the memory overhead of these large numbers of instances?

How do I do it?

First of all, it is important to understand that classes in python can dynamically add attributes, in fact, there is a __dict__ method in memory that maintains such dynamically added attributes, and it occupies memory, so if you turn it off, won't you be able to achieve the memory-saving requirement?

#!/usr/bin/python3
 
import time
import sys
 
 
class Player(object):
  def __init__(self, id, name, status):
     = id
     = name
     = status
 
if __name__ == '__main__':
  player_1 = Player(1, 'bei_bei', 'Going live')
  print(player_1.__dict__)
   
  print('_' * 100)
  # Dynamic assembly properties
  player_1.money = 10000
  player_1.__dict__['time'] = ()
  print(player_1.__dict__)
  print(player_1.money, player_1.time)
   
  print('_' * 100)
  # Print the amount of memory space occupied by __dict__.
  print('The dict method takes up memory:', (player_1.__dict__))
   
  print('_'*100)
  # Dynamically remove attributes
  print(player_1.__dict__)
  del player_1.__dict__['time']
   
  del player_1.money
  print(player_1.__dict__) 

Declare a list of instance attribute names via the __slots__ attribute

#!/usr/bin/python3
 
 
class Player(object):
  # Specify the fixed-length attribute of a class via the slots method
  __slots__ = ['id', 'name', 'status']
   
  def __init__(self, id, name, status):
     = id
     = name
     = status
 
 
if __name__ == '__main__':
  player_1 = Player(1, 'bei_bei', 'Going live')
  print(player_1.id, player_1.name, player_1.status)
   
  # Try to output the __dict__ attribute and find that without it, you can't dynamically assemble class attributes to save memory
  try:
    print(player_1.__dict__)
  except Exception as e:
    print(e)

This is the whole content of this article.