-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Description
The AgentSet class, which serves as the core container for model.agents an
FF8
d other groups, is backed by a weakref.WeakKeyDictionary. This design choice ensures that if an agent is deleted elsewhere in the code, it is automatically removed from the AgentSet, preventing memory leaks and "ghost" agents. However, this safety mechanism imposes a significant performance penalty .When iterating over a WeakKeyDictionary, Python must:
- Iterate over the weak reference objects.
- Call the weak reference to retrieve the actual object.
- Check if the object is None (garbage collected).
- Yield the object.
For the main Model.agents container, this overhead is redundant. The Model class explicitly manages the lifecycle of these agents via register_agent and deregister_agent, and it holds hard references in self._agents. Therefore, the agents in Model.agents will never be implicitly garbage collected while the model is running. We are effectively paying a performance penalty for a safety feature that is unnecessary in the simulations.