Cache and queries

This is just a general question.

I’m currently learning ECS and having some problems with number of entities found on IEntityJobs. I resize input arrays to those jobs using CalculateEntityCount() and then some indices fail. I’m wondering if this is something related to some “caching” that I’ve heard about.

I often see mentions to “this query is cached”, or the “query cache” or such things.

So, there’s a bunch of ways to create queries. I have no idea about the differences on speed, and convenience. When you create a EntityQuery on the OnCreate of a System, later you can use that query in OnUpdate.

  • Are queries cached from frame to frame?
  • Do CalculateEntityCount updates when matching entities number change?
  • Is there any particular thing to be aware of when using queries related to caching?
  • Does EntityQuery update everyframe if you use it?

I’ve read all documents in the manual. There’s not a single mention to “cache” or “caching”. But since everyone talks about it, I’m confused.

Query caching could be in reference to persistently storing an EntityQuery instead of calling SystemState.GetEntityQuery/EntityManager.CreateEntityQuery multiple times. There is also internal caching of the chunks that match each query which reduces the work needed if the cache is still valid. It would help if you pointed to any such reference to see what the context of the conversation is.

Different EntityQuery instances that have the same exact query (i.e. different systems that ask for an EntityQuery with the same exact components) point to shared state that retains an internally cached collection of matching chunks.

This value is computed on call, every time. Enableable components could dynamically change the number of entities matching a query.

Store and reuse the same EntityQuery instance. Creating ones with SystemState.GetEntityQuery each time adds needless overhead for searching queries it’s tracking. SystemAPI.QueryBuilder on the other hand codegens one-off creation of the query, so you don’t need to be concerned with using that in OnUpdate in that case.

The main state that matters is the query having a valid cached collection of which chunks it matches, which is updated on-demand as operations on the entity query are performed. Depending on how structural changes and usage of the EntityQuery occurs, this can happen several times in a given frame.

This stuff is mostly implementation details. The thing that really matters from an end user’s perspective - and the only thing users have any control over - is creating any given query as few times as possible within a system.

1 Like