EasyEcs

Change tracking

Visit only the entities whose component was written or removed since a system last ran, with ITrackChanges, [Changed<T>] and [Removed<T>] in C#.

Some systems only care about what changed: replicating state to clients, saving dirty entities, rebuilding a spatial index for the units that moved. Mark the component ITrackChanges and give the method [Changed<T>]: it visits only the entities whose T was written since its system last ran. [Removed<T>] is the counterpart for what went away: it visits the entities that lost T since then.

When to use it

Use it for

Following the few entities that changed: replication to clients, saving dirty entities, re-indexing moved units, and sending what was removed (a status that ended, a shield that broke).

Skip it for

Components rewritten on every row every tick, such as Position of units that always move: there is nothing to skip, and each write pays for its tick. Track the component a consumer reads, not every component.

How to use it

Mark the component

ITrackChanges gives the component a hidden column of ticks: every write records when it happened.

public record struct Health(int Value) : IComponent, ITrackChanges;
public record struct Replica(int Health) : IComponent;

Filter the method

[Changed<Health>] selects the rows written after the system's last run. Read the tracked component with in.

Replicate.cs
public class Replicate : EcsSystem
{
    // Only entities whose Health was written since this system's previous run
    // (all of them on its first run).
    [ForEach, Changed<Health>] 
    static void Copy(in Health health, ref Replica replica) => replica.Health = health.Value;
}

Write as usual

Any system or outside code that writes Health through a ref marks the row. Nothing else needs to change.

world.AddSystem<Replicate>();
unit.SetHealth(40);   // a write: Replicate sees this unit on its next run
world.Update();

What counts as a write

Every row of a tracked component records the world's change tick of its last write. A write is any access that hands out a ref, whether or not the code stores through it:

WriteNot a write
ref T parameters of [ForEach] methods (Span<T> for batch methods) and of struct jobs (Writes)in T parameters, ReadOnlySpan<T>
Query items (the enumerator stamps every row it visits)TryGet<T>(out T) (a copy), Read<T>() (read-only)
entity.Get<T>(), TryGetRef<T>(out found) when found, GetOrAdd<T>(), Set(...)Has<T>()
CreateEntity(...), CreateEntities(...), Instantiate(...), Clone() with the componentremoving the component (a removal)
entity.Enable<T>(), world.EnableAll<T>() (the kept value comes back)entity.Disable<T>() (a removal)
world.Restore(snapshot), world.Load(bytes), LoadEntities(...), LoadEntitiesInto(...) (every restored or loaded row)LoadEntitiesInto(..., markWritten: false): every component the record holds gets tick 0, replaced or added. For restoring a persisted record without saving or sending it back (a restored record). world.Load(bytes, markWritten: false): every loaded row gets tick 0 and no row counts as removed, for a restart that resumes a saved world (restart)
entity.Run<…>(ref job) (one entity): the components in the job's Writes (all of them unless the job overrides Writes; declare Writes => 0 for a read-only job), stamped only when Run returns trueentity.Run that returns false: the job did not run

A DynamicBuffer<T> is a list that can only change through a ref, so its writes are always tracked.

Ticks

world.ChangeTick grows by one per stage of systems (the systems with no order and no conflict between them that may run at once, or a single system) and once after each update, so writes between updates are newer than every system's last run. system.LastRunTick is the tick a system last ran at. A [Changed<T>] method selects rows written after it, so a system's own writes in one run are not changes for its next run. A new system starts at 0: its first run visits every row written since the world began (rows with tick 0, never written, excluded). world.AddSystem<T>(changesFromNow: true) starts it at the current tick instead, so its first run visits only what is written after it was added: for a system switched on in a world that already holds its state. Systems that write T never share a parallel stage with a [Changed<T>] or [Removed<T>] reader: the method declares a read of T.

Outside systems, filter by a tick you read earlier:

ulong mark = world.ChangeTick;
unit.SetHealth(40);                                                 // a write after the mark
var changed = QueryFilter.Create().Changed<Health>(mark);           // rows written at or after mark
int count = world.Count<Health>(changed);
foreach (var item in world.Query<Health>(changed))                  // items hand out refs: rows count as written
    Console.WriteLine($"{item.Entity}: {item.Health.Value} hp");

The tick is part of the call because a change is relative to someone's last look: [Changed<T>] methods use their system's last run, ad-hoc queries the mark the caller took. Tick 0 selects every row that has T.

Removal detection

Replication has to tell clients when something goes away too: a fire went out, a shield broke, a buff expired. [Removed<T>] visits the entities that lost a tracked component T since the system last ran:

ReplicateFire.cs
public record struct Burning(int Ticks) : IComponent, ITrackChanges;   // tracked: removals are recorded too
public record struct FireReplica(bool Burning) : IComponent;              // what the clients know of the fire

public class ReplicateFire : EcsSystem
{
    [ForEach, Changed<Burning>]                     // set on fire (or the fire written) since the last run
    static void Lit(ref FireReplica replica) => replica.Burning = true;

    [ForEach, Removed<Burning>]                     // the fire went out since the last run
    static void Out(ref FireReplica replica) => replica.Burning = false;
}

This works because removing a component keeps the entity's row: the row clears its presence bit, and a tracked component's removal stamps the row's change tick. A removed row is a row like any other, so the method reads and writes the entity's other components, and a batch method receives removed rows in runs.

Outside systems, QueryFilter.Removed<T>(since) does the same from a tick you read earlier, and shares the filter's one tick with its Changed filters (Since(tick) moves both):

// A field of your class: the tick is set per call.
private static readonly QueryFilter FireOut = QueryFilter.Create().Removed<Burning>(0);

ulong mark = world.ChangeTick;
world.Update();
int extinguished = world.Count<FireReplica>(FireOut.Since(mark));
foreach (var item in world.Query<FireReplica>(FireOut.Since(mark))) item.FireReplica.Burning = false;

Full example

Replication of health and of fires that went out, over a thousand units: the first update sends every row, later ones only what was written, and the removal of Burning is reported once. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

tick 1: sent 1000 of 1000 rows
  Entity 0v1: the fire went out at 80 hp
tick 2: sent 1 of 1000 rows
tick 3: sent 1 of 1000 rows
tick 4: sent 0 of 1000 rows
written since the mark: 2

The first run visits every row: all of them are new to it. On tick 2 the burning unit is written and loses Burning, so it is both sent and reported once; on tick 3 only the unit written from outside is sent; on tick 4 nothing was written and nothing is visited.

How to use it fast

  • Read with in. A ref parameter that only reads marks every row it visits as changed, and every [Changed<T>] reader downstream then visits them all.
  • Prefer a system to a query. A [Changed<T>] method skips unwritten tables, 4,096-row blocks and 64-row words before it touches a row. A Query hands out refs, so it stamps what it visits; a reader that must not mark what it reads (a save, a send) uses a struct job with Writes => 0 or entity.Read<T>().
  • Keep filters in static readonly fields and move their tick with Since(mark) instead of building a filter per call.
  • Take marks right after an update. Writes between two updates share one tick, so a mark taken in the middle of them also selects the writes made before it.

Measured on one system over 100,000 rows of a tracked component (ChangeTrackingBenchmark):

Rows written since the last run[Changed<T>]Plain [ForEach] over every row
10525 ns38.6 μs (73× slower)
1,000 scattered38.9 μs67.2 μs (1.73× slower)

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

A few writes, or writes to neighbouring rows, skip almost the whole walk. A thousand writes scattered over 100,000 rows touch most 64-row words, and then the saving is mostly the method calls that do not run.

What it costs

  • Memory: a hidden column of 8-byte ticks in every table that has the component.
  • Each write stores one tick and updates the summary of its 64-row word; a run of rows stores them with one vectorized fill.
  • Each pass skips a table nobody wrote with one load, then unwritten 4,096-row blocks and 64-row words (four per SIMD compare), and takes the written rows of a word from its summary.
  • A removal costs the same as a write: one tick and its word's summary.
  • Components without ITrackChanges pay nothing: the checks are JIT-time constants.

All of it on one page with the other features: Performance guide.

Pitfalls

MistakeWhat happensCaught by
Changing a collection inside a component through inThe row is not stamped, so [Changed<T>] misses itEECS011
[Removed<T>] on a method that also requires TAsks for rows that have and lack T at once: no row passesEECS016
[Removed<T>] with no component parameter or [With<U>]Nothing names what the method iteratesEECS003
ref parameter that only readsEvery visited row counts as changedEECS025
LoadEntitiesInto(..., markWritten: false) for values the receivers do not have yetThe loaded rows are not changes, so [Changed<T>] replication never sends themCode review: a replicator to new clients sends the full state itself
Expecting destroyed entities in [Removed<T>]They have no row and are never reportedMark with a tag, destroy after replicating
Several Changed / Removed filters with different ticksArgumentException: a filter has one tickAt run time

Compared with other libraries

Other libraries detect changes with dirty tags you add and clear yourself, and removals with events (one callback per removal, Friflo's OnComponentRemoved), with a reactive set completed by hand each tick (DefaultEcs' WhenRemoved<T>()), or not at all. Here a change or a removal is data that the next pass selects.

Find the 1,000 of 100,000 entities written since the last look

  • EasyEcs
  • Other libraries
EasyEcs: Changed0 B allocated38.5 μsEasyEcs: Scan1.59× · 0 B allocated61.4 μsDefaultEcs: WhenChanged2.01× · 0 B allocated77.3 μsFriflo.Engine.ECS: Scan1.40× · 0 B allocated53.7 μsFriflo.Engine.ECS: DirtyTag3.2× · 0 B allocated123 μsArch: Scan2.83× · 0 B allocated109 μsArch: DirtyTag2.18× · 0 B allocated84.0 μs0.00 ns20.0 μs40.0 μs60.0 μs80.0 μs100 μs120 μ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
EasyEcsChanged38.5 μs1.00×0 B
EasyEcsScan61.4 μs1.59×0 B
DefaultEcsWhenChanged77.3 μs2.01×0 B
Friflo.Engine.ECSScan53.7 μs1.40×0 B
Friflo.Engine.ECSDirtyTag123 μs3.2×0 B
ArchScan109 μs2.83×0 B
ArchDirtyTag84.0 μs2.18×0 B

The full comparison, with ten written rows and with removals: Comparison: change tracking.

Edit on GitHub

Last updated on

How is this guide?

On this page