EasyEcs

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

NeedUse
Per-entity logic of a systema [ForEach] method
Arithmetic over many rows in a systema batch [ForEach] method (spans, SIMD)
Heavy per-entity work in a system[ForEach(Parallel = true)]
A component the entity may or may not havea Maybe<T> parameter, or two methods split by With / Without
A pass outside systems, as a methoda [ForEach] runner: a static method with a generated entry point
The fastest ad-hoc loopworld.ForEach<T1..Tn, TJob>(ref job, filter) with a struct job
Ad-hoc loop that needs the Entityworld.ForEachEntity<T1..Tn, TJob>(ref job, filter)
Ad-hoc arithmetic over runs of rowsworld.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 threadsForEachParallel / 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 matchworld.DestroyEntities<T1..Tn>(filter)
Only rows written or removed since a tickChanged<T>(tick) / Removed<T>(tick) (change tracking)
Entities by a value, or pointing at an entityworld.Index<T, TKey>().Find(key) (indexes)

Filters

FilterSelectsAs 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>(), repeatedentities 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 groupnone; 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: keep item.Entity instead;
  • item.Position (named after the component) and item.Component1 are the same ref; named members are generated for each Query<...> 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 with Writes => 0, a [ForEach] method with in parameters, or entity.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> with world.ForEachEntity also receives the Entity, built from the table's entity rows without a lookup.
  • IForEachBatch<T1..Tn> with world.ForEachBatch receives runs of consecutive rows as spans, Execute(EntitySpan entities, Span<T1> …), to vectorize with Vector<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 alive

Without 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 in Writes are copied to the entity's new row after Execute, also when it throws, so what was written before the exception stays.
  • Only Writes count as written for change tracking, and only when Run returns true. The default, Writes => -1, stamps every component the job takes; a job that writes nothing declares Writes => 0.
  • false is not "dead": it also means a missing component or a filter that failed. Test entity.IsAlive when the reason matters.
  • INoStructuralChanges skips the bookkeeping and freezes the structure while the job runs, like a pass: a structural change made anyway throws InvalidOperationException.
  • 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 a static readonly field.
  • For the analyzer, Run is a structural change (its job may make one), rejected where those are: in a parallel [ForEach] method (EECS010), in a [ForEach] method that takes no Entity or World (EECS013) and off the world's owner thread (EECS014).

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):

CaseComponentsFilteredStructuralMeanvs baselineAllocated
Handwritten1FalseFalse15.9 μs1.00×0 B
Run1FalseFalse14.0 μs0.88×0 B
Handwritten1FalseTrue33.5 μs1.00×0 B
Run1FalseTrue27.9 μs0.84×0 B
Handwritten1TrueFalse16.2 μs1.00×0 B
Run1TrueFalse14.8 μs0.91×0 B
Handwritten1TrueTrue32.8 μs1.00×0 B
Run1TrueTrue28.1 μs0.86×0 B
Handwritten3FalseFalse23.4 μs1.00×0 B
Run3FalseFalse16.1 μs0.69×0 B
Handwritten3FalseTrue34.1 μs1.01×0 B
Run3FalseTrue33.5 μs0.99×0 B
Handwritten3TrueFalse21.6 μs1.00×0 B
Run3TrueFalse20.9 μs0.97×0 B
Handwritten3TrueTrue31.2 μs1.00×0 B
Run3TrueTrue32.4 μs1.04×0 B
Handwritten5FalseFalse27.5 μs1.00×0 B
Run5FalseFalse24.4 μs0.89×0 B
Handwritten5FalseTrue35.6 μs1.00×0 B
Run5FalseTrue37.7 μs1.06×0 B
Handwritten5TrueFalse28.2 μs1.00×0 B
Run5TrueFalse24.3 μs0.86×0 B
Handwritten5TrueTrue35.2 μs1.01×0 B
Run5TrueTrue37.0 μs1.06×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

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 threads

The 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: 11

The 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 ofDoWhy
A Query loop every tickA [ForEach] method in a systemGenerated struct job, ordered and scheduled
QueryFilter.Create()… at every callA static readonly filterThe cache key is built once
A Query that only reads tracked componentsA job with Writes => 0, or in parametersItems stamp what they hand out
ForEachEntity when the entity is rarely usedA batch job with EntitySpanHandles built only for the rows that need one
A scalar loop over many rowsA batch job with Vector<T>The JIT does not vectorize on its own
Count(...) > 0Any(...)Stops at the first match (EECS032)
Several Get / TryGetRef and a Has<Dead>() per requestentity.Run with a static readonly filterOne lookup; the refs are carried across structural changes
Scanning for a keyA value indexO(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):

CaseMeanvs baselineAllocated
RawArrayWrite12.8 μs1.01×0 B
ForEachSystemWrite9.13 μs0.72×0 B
ForEachWrite9.55 μs0.75×0 B
QueryWrite18.9 μs1.49×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

A pass outside systems over 100,000 entities with a filter: a [ForEach] runner, the struct job it replaces and a Query loop (RunnerBenchmark):

CaseMeanvs baselineAllocated
Runner33.7 μs1.00×0 B
HandWrittenJob56.7 μs1.69×0 B
Query145 μs4.3×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

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):

CaseMeanvs baselineAllocated
FilterAtCall74.8 ns1.00×0 B
FilterOnce21.6 ns0.29×0 B
NoFilter42.9 ns0.57×0 B
PastTheMemo88.0 ns1.18×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

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):

CaseMeanvs baselineAllocated
PassOverTheFew386 ns—0 B
QueryTheFew365 ns—0 B
CountTheFew13.6 ns—0 B
PassOverTheRest52.3 μs—0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

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
Iterate1Friflo.Engine.ECS 1.59×37.7 μs · 0 B59.9 μs · 0 BIterate2Friflo.Engine.ECS 1.02×253 μs · 0 B257 μs · 0 BIterate2SimdFriflo.Engine.ECS 1.16×69.5 μs · 0 B80.7 μs · 0 BWithFriflo.Engine.ECS 1.46×11.3 μs · 0 B16.6 μs · 0 B0.00 ns50.0 μs100 μs150 μs200 μs250 μsTime (shorter is faster)

BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Data table
LibraryCaseMeanvs EasyEcsAllocated
EasyEcsIterate137.7 μs1.00×0 B
Friflo.Engine.ECSIterate159.9 μs1.59×0 B
EasyEcsIterate2253 μs1.00×0 B
Friflo.Engine.ECSIterate2257 μs1.02×0 B
EasyEcsIterate2Simd69.5 μs1.00×0 B
Friflo.Engine.ECSIterate2Simd80.7 μs1.16×0 B
EasyEcsWith11.3 μs1.00×0 B
Friflo.Engine.ECSWith16.6 μs1.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.
  • Count is 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

MistakeWhat happensCaught by
await inside a Query loopDoes not compile: items are ref structsThe C# compiler
Storing a query itemDoes not compile; keep item.EntityThe C# compiler
A Query loop that only reads tracked componentsEvery visited row counts as writtenUse a job with Writes => 0 or Read<T>()
INoStructuralChanges on a job that changes structureInvalidOperationException at the changeAt run time
Structural change in a batch jobInvalidOperationException: the spans point into the tablesAt run time (EECS013 for [ForEach] methods)
A parallel job that writes a singleton or another entityRaces between chunksCode review (EECS010 for [ForEach] methods)
Changed and Removed with different ticks in one filterArgumentExceptionAt run time
Update() called from inside a query loop of the same worldUndefined order of passesCode review; EECS034 when called from a system
An entity.Run job without WritesThe default (-1) stamps every tracked component the job takesDeclare Writes (0 for a job that only reads)
INoStructuralChanges on a Run job that changes structureInvalidOperationException at the changeAt run time
Treating false from Run as "dead"It also means a missing component or a filter that failedCode review: test IsAlive
QueryFilter.Create()… built at every Run or query callThe filter is rebuilt and looked up at every callCode review: a static readonly field
entity.Run inside a parallel [ForEach] methodIts job may change structure from several threadsEECS010
Edit on GitHub

Last updated on

How is this guide?

On this page