Query caching is one of the most impactful performance optimizations in jecs. Understanding when and how to use cached queries can dramatically improve your game’s performance.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/Ukendio/jecs/llms.txt
Use this file to discover all available pages before exploring further.
What is Query Caching?
Jecs is an archetype ECS: entities with the same components are grouped together in an “archetype”. When you create or modify entities, archetypes are created on the fly.Archetypes in Action
e1is in archetype[Position, Velocity]e2is in archetype[Position, Velocity, Mass]
How Caching Works
Without Caching (Uncached Query)
Every time you run an uncached query, it:- Searches through all archetypes
- Checks which archetypes match your component requirements
- Iterates over matching entities
With Caching (Cached Query)
A cached query:- First time: Searches archetypes and builds a cache of matching archetypes
- Subsequent times: Directly iterates the cached archetype list (no search needed)
Even as entities move in and out of archetypes, the archetypes themselves remain stable. This makes caching extremely effective.
Performance Benefits
Cached queries don’t have to search—they just iterate a pre-matched list. This is:- Much faster for repeated queries (e.g., every frame in a system)
- Minimal overhead once the cache is built
Uncached vs Cached Queries
Uncached Query (Default)
- Query is run once or infrequently
- Query is ad-hoc (conditions only known at runtime)
- You’re prototyping and don’t know query frequency yet
Cached Query
- Query runs every frame (systems)
- Query is long-lived and reused
- Performance matters more than setup time
Tradeoffs
| Aspect | Uncached | Cached |
|---|---|---|
| Iteration speed | Slower | Much faster |
| Creation time | Instant | Slower (builds cache) |
| Archetype creation overhead | None | Small (cache update) |
| Memory | Minimal | Small cache overhead |
| Best for | Ad-hoc, one-off queries | Repeated, per-frame queries |
When to Avoid Caching
-
Ad-hoc queries: Queries with runtime-specific conditions
-
One-time queries: Queries that run once or rarely
- Prototype/exploration: When you’re still figuring out your systems
When to Use Caching
-
Systems that run every frame:
-
Frequently reused queries:
Complete Example
Rule of Thumb
Frame-rate systems → Use
.cached()If your query runs every frame (or even multiple times per frame), caching provides a massive performance boost.One-off or runtime-specific queries → Don’t cacheIf your query runs occasionally or has conditions only known at runtime, uncached queries are simpler and fine.
Cache Invalidation
Caches automatically update when:- New archetypes are created
- Archetypes are deleted
Next Steps
Relationships
Learn about entity relationships and hierarchies
Hooks & Signals
React to component lifecycle events