[Proposal] Event-driven live entity caching for MetaAgents (resolving TODO(perf))
Hi @EdgeofChaos @falloficaruss @quaquel,
Following up on the recent Meta-Agents rewrite (#3811), I looked into the open TODO(perf) in mesa/meta_agents/meta_agents_api.py:93:
# TODO(perf): This rebuilds an O(N) mapping over every model agent on each call. Cache the lookup instead and only rebuild it on agent add or remove calls...
Currently, _live_entity_lookup() iterates over self.model.agents on every query, which runs multiple times per members_of() or groups_of() call. For simulations with larger agent counts:
- Current (Uncached): 1,000
members_of()queries across 5,000 agents take ~0.39s. - With Event-Driven Cache: 1,000 queries take ~0.001s (a 300x+ speedup).
Proposed Approach:
- Add
_register_agent_added_hooktomesa.Model(symmetrical to the existing_register_agent_removed_hook). - Maintain an internal
_live_entity_cacheinMetaAgentssynchronized via model addition/removal lifecycle hooks and initialized once on__init__. - Return the cached dictionary directly in
_live_entity_lookup().
I have drafted the implementation and regression tests in #3828.
Please take a look and let me know if you would like me make any changes or if you'd go some other way than i currently am :)) . IUt It is also completely fine if you'd have any core members actually doing so than contributors, i missed the part where i had to open a discussion or an issue before opening a PR so i went converted it to a draft and opened this issue for discussion. Thank youu
closing this, since this project was assigned to @ tpike3 .