E407 Do we really need weakrefs in AgentSet? · Issue #3128 · mesa/mesa · GitHub
[go: up one dir, main page]

Skip to content

Do we really need weakrefs in AgentSet? #3128

@codebreaker32

Description

@codebreaker32

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:

  1. Iterate over the weak reference objects.
  2. Call the weak reference to retrieve the actual object.
  3. Check if the object is None (garbage collected).
  4. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0