Move global user storage from WeakValueDictionary to dict

Profiling showed that WeakValueDictionary caused rather significant
and noticeable slowdowns during startup. Since the only thing it was
used for was to automatically remove the key from the mapping when
the reference count reaches zero, the same could theoretically be
accomplished by using the __del__ special method. There is a chance
that this could lead to a memory leak since the __del__ method is not
always called, but the only instances of this happening are during
interpreter shutdown to my knowledge and at that point the mapping
is the least of my concern.
This commit is contained in:
Rapptz
2021-07-05 21:01:40 -04:00
parent 88d825a803
commit cb2363f0fd
2 changed files with 44 additions and 6 deletions

View File

@ -322,11 +322,28 @@ class User(BaseUser, discord.abc.Messageable):
Specifies if the user is a system user (i.e. represents Discord officially).
"""
__slots__ = ('__weakref__',)
__slots__ = ('_stored',)
def __init__(self, *, state, data):
super().__init__(state=state, data=data)
self._stored = False
def __repr__(self):
return f'<User id={self.id} name={self.name!r} discriminator={self.discriminator!r} bot={self.bot}>'
def __del__(self) -> None:
try:
if self._stored:
self._state.deref_user(self.id)
except Exception:
pass
@classmethod
def _copy(cls, user):
self = super()._copy(user)
self._stored = getattr(user, '_stored', False)
return self
async def _get_channel(self):
ch = await self.create_dm()
return ch