Queries and filters
Select entities with a set of components, with or without others, or changed since a tick: Query loops, struct jobs, Count, Any, QueryFilter and costs.
A query selects the entities that have a set of components (1 to 9), optionally filtered: with or without other
components, one of a group, or only those written or removed since a tick. Systems use queries through [ForEach]
methods; code outside systems (an admin request, a test, a tool between ticks) calls them directly. Every query API
is allocation-free.
When to use it
Use it for
Iteration outside systems: request handlers between updates, tools, tests, one-off passes. Jobs on one entity
(entity.Run): the handler of a request or of a message to an actor. Counts and existence
checks (Count, Any). Bulk destroys (DestroyEntities<T>(filter)). The filters themselves, which [ForEach]
methods take as attributes.
Skip it for
Per-tick logic: write a [ForEach] method in a system instead. It is
generated, ordered with the other systems, scheduled in parallel stages and as fast as the fastest hand-written
loop. Looking entities up by a value or by the entity they point at: use an
index, not a scan.
How to use it
Build the filter once
QueryFilter is a value built with chained calls. Keep each one in a static readonly field.
public static class Filters
{
public static readonly QueryFilter Active = QueryFilter.Create().Without<Frozen>().Without<Dead>();
public static readonly QueryFilter Impaired = QueryFilter.Create().WithAny<Frozen>().WithAny<Stunned>(); // either
}Loop over the matches
world.Query<T1..Tn>(filter) is a foreach loop. Each item hands out refs into the table, named after the
components, and the entity.
var world = new World();
world.CreateEntity(new Position(0, 0), new Velocity(1, 0));
world.CreateEntity(new Position(0, 0), new Velocity(0, 1), new Frozen());
foreach (var item in world.Query<Position, Velocity>(Filters.Active))
{
ref var p = ref item.Position; // a ref into the table
p.X += item.Velocity.X;
if (p.X > 100) item.Entity.SetDead(); // structural changes are allowed
}Count and test
int moving = world.Count<Position, Velocity>(Filters.Active);
bool anyImpaired = world.Any<Position>(Filters.Impaired); // stops at the first match
int cleared = world.DestroyEntities<Position>(QueryFilter.Create().With<Dead>());Which API
| Need | Use |
|---|---|
| Per-entity logic of a system | a [ForEach] method |
| Arithmetic over many rows in a system | a batch [ForEach] method (spans, SIMD) |
| Heavy per-entity work in a system | [ForEach(Parallel = true)] |
| A component the entity may or may not have | a Maybe<T> parameter, or two methods split by With / Without |
| A pass outside systems, as a method | a [ForEach] runner: a static method with a generated entry point |
| The fastest ad-hoc loop | world.ForEach<T1..Tn, TJob>(ref job, filter) with a struct job |
Ad-hoc loop that needs the Entity | world.ForEachEntity<T1..Tn, TJob>(ref job, filter) |
| Ad-hoc arithmetic over runs of rows | world.ForEachBatch<T1..Tn, TJob>(ref job, filter) |
| A job on one entity (a request, a message) | entity.Run<T1..Tn, TJob>(ref job, filter) |
| Ad-hoc heavy work on several threads | ForEachParallel / ForEachEntityParallel |
| A convenient loop (tools, tests, handlers) | foreach (var item in world.Query<T1..Tn>(filter)) |
| "How many …?" / "Is there any …?" | world.Count<T1..Tn>(filter) / world.Any<T1..Tn>(filter) |
| Destroy every match | world.DestroyEntities<T1..Tn>(filter) |
| Only rows written or removed since a tick | Changed<T>(tick) / Removed<T>(tick) (change tracking) |
| Entities by a value, or pointing at an entity | world.Index<T, TKey>().Find(key) (indexes) |
Filters
| Filter | Selects | As a [ForEach] attribute |
|---|---|---|
With<T>() | entities that also have T (not passed in) | [With<T>] |
Without<T>() | entities that lack T | [Without<T>] |
WithAny<T>(), repeated | entities with at least one of the WithAny components | [WithAny<T>], repeated |
Changed<T>(since) | entities whose tracked T was written at or after since | [Changed<T>] (since the system's last run) |
Removed<T>(since) | entities that lost tracked T at or after since and still lack it | [Removed<T>] |
InGroup<T>(group) | entities whose T is in one group | none; the generated filter.InTeam(group) for an IGroup component Team |
Since(tick) | the same filter, its Changed and Removed moved to another tick |
Every filter can be repeated and combined. A filter holds one tick: its Changed and Removed parts must name the
same one (else ArgumentException), and Since(tick) moves them together, so a filter kept in a field is reused
after every update:
public record struct Armor(int Value) : IComponent, ITrackChanges;
public static class Replication
{
public static readonly QueryFilter Dirty = QueryFilter.Create().Changed<Armor>(0);
}ulong mark = world.ChangeTick;
world.Update();
int dirty = world.Count<Armor>(Replication.Dirty.Since(mark));Query: a foreach loop
The enumerator and its items are ref structs holding refs into the current table, so:
- a query loop cannot contain
await, and an item cannot be stored: keepitem.Entityinstead; item.Position(named after the component) anditem.Component1are the same ref; named members are generated for eachQuery<...>shape your code calls;- items count as a write of every tracked (
ITrackChanges) component they hand out, whether or not the loop stores through them. To read tracked components without marking them (a save, a send), use a struct job withWrites => 0, a[ForEach]method withinparameters, orentity.Read<T>()(what counts as a write).
A loop may create, destroy, add and remove; the rules are in Structural changes.
ForEach: a struct job
A struct that implements IForEach<T1..Tn> is specialized for its type and inlined by the JIT: no delegate, no
closure, no allocation. [ForEach] methods compile to exactly this.
public struct Integrate : IForEach<Position, Velocity>, INoStructuralChanges
{
public static int Writes => 1; // Position (component 1); Velocity is only read
public void Execute(ref Position p, ref Velocity v)
{
p.X += v.X;
p.Y += v.Y;
}
}var integrate = new Integrate();
world.ForEach<Position, Velocity, Integrate>(ref integrate, Filters.Active);The job is passed by ref, so fields it accumulates (a sum, a count) are visible after the call. It receives the
components only, so the pass never loads the entity rows. A job that must hold a ref or a Span can be a
ref struct, except for the *Parallel calls.
What a job declares: Writes
Job parameters are all ref, so a job says which components it actually writes with an optional
static int Writes: bit k - 1 for component k, default -1 (all of them). Only those count as written for
change tracking, and only those are carried over to the entity's new row when the
job changes the archetype of the entity it visits. INoStructuralChanges promises that Execute never creates,
destroys, adds or removes: the pass then skips the bookkeeping that keeps changes safe and freezes the structure, so
a change made anyway throws instead of tearing rows. Generated [ForEach] jobs set both from the method.
With the entity, or in runs of rows
IForEachEntity<T1..Tn>withworld.ForEachEntityalso receives theEntity, built from the table's entity rows without a lookup.IForEachBatch<T1..Tn>withworld.ForEachBatchreceives runs of consecutive rows as spans,Execute(EntitySpan entities, Span<T1> …), to vectorize withVector<T>(the JIT does not vectorize loops on its own).entities[i]is built only when indexed. The spans point into the tables, so a structural change throws while the job runs.
using System.Numerics;
using System.Runtime.InteropServices;
public struct KillTheWounded : IForEachEntity<Health>
{
public static int Writes => 0; // reads Health; the change is structural (a tag)
public void Execute(Entity unit, ref Health hp)
{
if (hp.Value <= 0) unit.SetDead();
}
}
public struct Drift : IForEachBatch<Position, Velocity>
{
public static int Writes => 1;
public void Execute(EntitySpan entities, Span<Position> positions, Span<Velocity> velocities)
{
// Two floats each: as Vector<float> spans, every lane is one coordinate
var p = MemoryMarshal.Cast<Position, Vector<float>>(positions);
var v = MemoryMarshal.Cast<Velocity, Vector<float>>(velocities);
for (int i = 0; i < p.Length; i++) p[i] += v[i];
var pf = MemoryMarshal.Cast<Position, float>(positions);
var vf = MemoryMarshal.Cast<Velocity, float>(velocities);
for (int i = p.Length * Vector<float>.Count; i < pf.Length; i++) pf[i] += vf[i]; // the rows left over
}
}var kill = new KillTheWounded();
world.ForEachEntity<Health, KillTheWounded>(ref kill, QueryFilter.Create().Without<Dead>());
var drift = new Drift();
world.ForEachBatch<Position, Velocity, Drift>(ref drift, Filters.Active);One entity: entity.Run
Code that handles one entity at a time runs a job on it with entity.Run<T1..Tn, TJob>(ref job, filter): a request
or a message to an actor, a command from a client. The job is an IForEachEntity job, the same type a pass over the
world takes, and gets the refs a pass gives it: one table lookup for all its components instead of one per Get.
It returns false, without running the job, when the entity lacks a component, fails the filter or is not alive.
public static class Hits
{
// Built once: the filter is a value, kept in a field.
public static readonly QueryFilter Alive = QueryFilter.Create().Without<Dead>();
}
public struct TakeHit : IForEachEntity<Health>
{
public int Damage;
public static int Writes => 1;
public void Execute(Entity unit, ref Health hp)
{
if (hp.Value <= Damage) unit.SetDead(); // a structural change: hp still points at the entity's value
hp.Value -= Damage; // carried over to its new row when the job returns
}
}var hit = new TakeHit { Damage = 30 };
bool applied = unit.Run<Health, TakeHit>(ref hit, Hits.Alive); // false: dead, no Health, or not aliveWithout a filter, entity.Run<T1..Tn, TJob>(ref job) checks only that the entity is alive and has the components.
A job that only reads declares Writes => 0:
public struct ReadHealth : IForEachEntity<Health>
{
public int Value;
public static int Writes => 0; // reads only: nothing counts as written
public void Execute(Entity unit, ref Health hp) => Value = hp.Value;
}var read = new ReadHealth();
if (unit.Run<Health, ReadHealth>(ref read)) Console.WriteLine(read.Value);- The refs survive the job's own structural changes, as in
ForEachEntity: the components inWritesare copied to the entity's new row afterExecute, also when it throws, so what was written before the exception stays. - Only
Writescount as written for change tracking, and only whenRunreturnstrue. The default,Writes => -1, stamps every component the job takes; a job that writes nothing declaresWrites => 0. falseis not "dead": it also means a missing component or a filter that failed. Testentity.IsAlivewhen the reason matters.INoStructuralChangesskips the bookkeeping and freezes the structure while the job runs, like a pass: a structural change made anyway throwsInvalidOperationException.- O(1), plus O(1) per component the filter names, unless the filter names a type past the first 256 (then it goes
through the query cache). A filter tests the row the way a query does (
Without,WithAny,Changed<T>(tick), groups), with no lookup of the query's tables; build it once, in astatic readonlyfield.
An actor is the typical user: each message handler finds the actor's entity (through a value index) and runs one job on it. The Actors sample is a whole program built this way.
1,000 calls, each on another of 10,000 entities, with 1, 3 or 5 components, with or without a Without<Dead> filter
and a structural change in the middle, against the same work written through the handle (Has<Dead>(), a
TryGetRef per component, the ref taken again after the change) (SingleEntityBenchmark):
| Case | Components | Filtered | Structural | Mean | vs baseline | Allocated |
|---|---|---|---|---|---|---|
| Handwritten | 1 | False | False | 15.9 μs | 1.00× | 0 B |
| Run | 1 | False | False | 14.0 μs | 0.88× | 0 B |
| Handwritten | 1 | False | True | 33.5 μs | 1.00× | 0 B |
| Run | 1 | False | True | 27.9 μs | 0.84× | 0 B |
| Handwritten | 1 | True | False | 16.2 μs | 1.00× | 0 B |
| Run | 1 | True | False | 14.8 μs | 0.91× | 0 B |
| Handwritten | 1 | True | True | 32.8 μs | 1.00× | 0 B |
| Run | 1 | True | True | 28.1 μs | 0.86× | 0 B |
| Handwritten | 3 | False | False | 23.4 μs | 1.00× | 0 B |
| Run | 3 | False | False | 16.1 μs | 0.69× | 0 B |
| Handwritten | 3 | False | True | 34.1 μs | 1.01× | 0 B |
| Run | 3 | False | True | 33.5 μs | 0.99× | 0 B |
| Handwritten | 3 | True | False | 21.6 μs | 1.00× | 0 B |
| Run | 3 | True | False | 20.9 μs | 0.97× | 0 B |
| Handwritten | 3 | True | True | 31.2 μs | 1.00× | 0 B |
| Run | 3 | True | True | 32.4 μs | 1.04× | 0 B |
| Handwritten | 5 | False | False | 27.5 μs | 1.00× | 0 B |
| Run | 5 | False | False | 24.4 μs | 0.89× | 0 B |
| Handwritten | 5 | False | True | 35.6 μs | 1.00× | 0 B |
| Run | 5 | False | True | 37.7 μs | 1.06× | 0 B |
| Handwritten | 5 | True | False | 28.2 μs | 1.00× | 0 B |
| Run | 5 | True | False | 24.3 μs | 0.86× | 0 B |
| Handwritten | 5 | True | True | 35.2 μs | 1.01× | 0 B |
| Run | 5 | True | True | 37.0 μs | 1.06× | 0 B |
On several threads: ForEachParallel and ForEachEntityParallel
A job that implements INoStructuralChanges and writes only its own row can run on several threads.
ForEachParallel (an IForEach job) and ForEachEntityParallel (an IForEachEntity job) cut the matching rows into
chunks (about four per thread, a multiple of 64 rows, between 1,024 and World.ParallelChunkRows = 16,384). The
calling thread and up to WorldOptions.MaxDegreeOfParallelism - 1 thread-pool threads run them, each with its own
copy of the job, so state accumulated in its fields is not merged back. Fewer than two chunks run on the calling
thread.
public struct Heal : IForEach<Health>, INoStructuralChanges
{
public static int Writes => 1;
public void Execute(ref Health health) => health.Value = Math.Min(health.Value + 10, 100);
}var heal = new Heal();
world.ForEachParallel<Health, Heal>(ref heal, Filters.Active); // each row runs once, on one of the threadsThe job must not read what another row's job writes (another entity, a singleton), and nothing else may change the
world during the call. [ForEach(Parallel = true)] compiles a system method
to the same chunked run.
Count and Any
Count sums the row counts of the matching tables, and counts presence bits only in tables where some rows lack a
queried component. Any stops at the first match. Neither touches a component value.
Full example
Filters in a system, then a query, a count and a struct job outside it. Three units move, one of them frozen, and
a fourth has no velocity at all. Put the files in a console project that references EasyEcs
(dotnet add package EasyEcs) and run it with dotnet run.
It prints:
Entity 0v1: Position { X = 1, Y = 0 }
Entity 2v1: Position { X = 1, Y = 1 }
moving: 2, any frozen: True
sum of X: 11The frozen unit stays where it was, and the burning one moves at half its speed. The unit without a velocity is
not a mover, but the job over Position alone counts it.
How to use it fast
| Instead of | Do | Why |
|---|---|---|
A Query loop every tick | A [ForEach] method in a system | Generated struct job, ordered and scheduled |
QueryFilter.Create()… at every call | A static readonly filter | The cache key is built once |
A Query that only reads tracked components | A job with Writes => 0, or in parameters | Items stamp what they hand out |
ForEachEntity when the entity is rarely used | A batch job with EntitySpan | Handles built only for the rows that need one |
| A scalar loop over many rows | A batch job with Vector<T> | The JIT does not vectorize on its own |
Count(...) > 0 | Any(...) | Stops at the first match (EECS032) |
Several Get / TryGetRef and a Has<Dead>() per request | entity.Run with a static readonly filter | One lookup; the refs are carried across structural changes |
| Scanning for a key | A value index | O(matches) instead of O(rows) |
The same write, Position += Velocity over 10,000 entities: two plain arrays (RawArrayWrite), a [ForEach]
system (ForEachSystemWrite), a hand-written struct job (ForEachWrite) and a Query loop (QueryWrite):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| RawArrayWrite | 12.8 μs | 1.01× | 0 B |
| ForEachSystemWrite | 9.13 μs | 0.72× | 0 B |
| ForEachWrite | 9.55 μs | 0.75× | 0 B |
| QueryWrite | 18.9 μs | 1.49× | 0 B |
A pass outside systems over 100,000 entities with a filter: a [ForEach] runner, the struct job it replaces and a
Query loop (RunnerBenchmark):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| Runner | 33.7 μs | 1.00× | 0 B |
| HandWrittenJob | 56.7 μs | 1.69× | 0 B |
| Query | 145 μs | 4.3× | 0 B |
The call itself, counting 16 entities: a filter built at the call, the same filter in a field, no filter, and a
filter past the per-signature memo (CallSiteBenchmark):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| FilterAtCall | 74.8 ns | 1.00× | 0 B |
| FilterOnce | 21.6 ns | 0.29× | 0 B |
| NoFilter | 42.9 ns | 0.57× | 0 B |
| PastTheMemo | 88.0 ns | 1.18× | 0 B |
A rare state in a big table: 10 burning units among 100,000 in one table. The walk skips the 64-row words without a
match (SparseBenchmark):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| PassOverTheFew | 386 ns | — | 0 B |
| QueryTheFew | 365 ns | — | 0 B |
| CountTheFew | 13.6 ns | — | 0 B |
| PassOverTheRest | 52.3 μs | — | 0 B |
Against Friflo.Engine.ECS on the same world: one component, two components scalar and with SIMD, and a With filter:
Iteration per pass, 100,000 entities
- EasyEcs
- Friflo.Engine.ECS
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
Data table
| Library | Case | Mean | vs EasyEcs | Allocated |
|---|---|---|---|---|
| EasyEcs | Iterate1 | 37.7 μs | 1.00× | 0 B |
| Friflo.Engine.ECS | Iterate1 | 59.9 μs | 1.59× | 0 B |
| EasyEcs | Iterate2 | 253 μs | 1.00× | 0 B |
| Friflo.Engine.ECS | Iterate2 | 257 μs | 1.02× | 0 B |
| EasyEcs | Iterate2Simd | 69.5 μs | 1.00× | 0 B |
| Friflo.Engine.ECS | Iterate2Simd | 80.7 μs | 1.16× | 0 B |
| EasyEcs | With | 11.3 μs | 1.00× | 0 B |
| Friflo.Engine.ECS | With | 16.6 μs | 1.46× | 0 B |
What it costs
- The first use of a query shape (components plus filter) visits every table once to build its cache entry. Tables created later join the entries they match.
- Every later call finds the entry through a small per-signature memo, or one hash probe past it, then walks O(matching tables + their rows).
- Filtered rows are tested 64 at a time from presence bits; words where every row passes are spanned four per SIMD compare, and words with no match are skipped.
Countis O(matching tables), plus a popcount per word in tables whose rows differ.- No allocation: filters are values with no object reference, enumerators and items are ref structs, jobs are structs.
Pitfalls
| Mistake | What happens | Caught by |
|---|---|---|
await inside a Query loop | Does not compile: items are ref structs | The C# compiler |
| Storing a query item | Does not compile; keep item.Entity | The C# compiler |
A Query loop that only reads tracked components | Every visited row counts as written | Use a job with Writes => 0 or Read<T>() |
INoStructuralChanges on a job that changes structure | InvalidOperationException at the change | At run time |
| Structural change in a batch job | InvalidOperationException: the spans point into the tables | At run time (EECS013 for [ForEach] methods) |
| A parallel job that writes a singleton or another entity | Races between chunks | Code review (EECS010 for [ForEach] methods) |
Changed and Removed with different ticks in one filter | ArgumentException | At run time |
Update() called from inside a query loop of the same world | Undefined order of passes | Code review; EECS034 when called from a system |
An entity.Run job without Writes | The default (-1) stamps every tracked component the job takes | Declare Writes (0 for a job that only reads) |
INoStructuralChanges on a Run job that changes structure | InvalidOperationException at the change | At run time |
Treating false from Run as "dead" | It also means a missing component or a filter that failed | Code review: test IsAlive |
QueryFilter.Create()… built at every Run or query call | The filter is rebuilt and looked up at every call | Code review: a static readonly field |
entity.Run inside a parallel [ForEach] method | Its job may change structure from several threads | EECS010 |
Related
Last updated on
How is this guide?
Prefabs and cloning
Define a kind of entity once as a Prefab and spawn it alone, in waves or as a linked group: derived prefabs, prefab buffers, EnsureCapacity and Entity.Clone.
Systems and [ForEach]
Write per-tick logic as stateless systems with [ForEach] methods: parameters, filters, ordering, groups, batch and parallel methods, runners and errors.