EasyEcs

Structural changes

Create, destroy, add and remove components in the middle of a pass. EasyEcs applies them at once, with no command buffer, visiting each entity at most once.

A structural change is anything that changes which components an entity has, or which entities exist: creating (CreateEntity, Instantiate, Clone), destroying, adding a component (Set, GetOrAdd of a missing one) or removing one. EasyEcs applies them immediately, even in the middle of a pass: there is no command buffer to record into and play back, so the death system marks a unit Dead where it decides, and the very next system already sees the corpse.

When to use it

Use it for

Changing entities where the decision is made: set Dead in the death system, destroy an expired projectile in its own loop, spawn a projectile in the system that fires it, add Stunned in the hit that stuns. Tags for states that come and go: removing a component and adding it back moves nothing.

Skip it for

Keeping a ref (other than the method's own ref parameters) across a structural change. Changing structure in a batch method, a parallel method or a job that implements INoStructuralChanges: their structure is frozen, and a change throws. A value that changes every tick: a field is cheaper than a component added and removed each tick.

How to use it

Take the Entity (or the World)

A [ForEach] method changes structure through its Entity parameter, or creates entities through its World parameter. The generator sees the parameter and gives the method a pass that notices the changes.

public record struct Lifetime(int Ticks) : IComponent;
public record struct Projectile(EntityId Owner) : IComponent;
public record struct Weapon(int Cooldown) : IComponent;

public class ExpireSystem : EcsSystem
{
    [ForEach]
    static void Expire(Entity shot, ref Lifetime life)
    {
        if (--life.Ticks <= 0) shot.Destroy();         // destroyed now, in the middle of the pass
    }
}

public class FireSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Fire(Entity shooter, ref Weapon weapon, in Position at, World world)
    {
        if (weapon.Cooldown-- > 0) return;
        weapon.Cooldown = 10;
        world.CreateEntity(at, new Lifetime(30), new Projectile(shooter.Id));   // not visited by passes already running
    }
}

Run them in one update

var world = new World();
world.AddSystem<FireSystem>();
world.AddSystem<ExpireSystem>();                     // sees this update's new projectiles
world.CreateEntity(new Position(0, 0), new Weapon(0));
world.Update();
int shots = world.Count<Projectile>();               // 1

Adding and removing while iterating

Inside [ForEach] methods, ForEach jobs and Query loops you can create and destroy entities and add or remove components, of the visited entity or any other. The rules:

  • A pass visits each entity at most once.
  • Entities that stop matching before their turn are skipped: destroyed, a queried component removed, or an excluded one added.
  • Entities that join a matching table during the pass are not visited by it: created, or moved into a matching table. The next pass sees them.
  • An entity that gets a queried component back without moving (its row only sets a presence bit) is visited if the pass has not reached its row yet.

no

yes

pass reaches a row

still matches?

skip

call the method

changes apply now

next row

Refs across a change

  • The method's own ref parameters stay writable when the body changes the visited entity's table: the pass copies those writes to the entity's new row after the body returns. in parameters keep showing the values from before the change.
  • Any other ref (from entity.Get<T>(), a Query item, or another entity) is guaranteed only until the next structural change: write through it before the change, or get it again afterwards.
  • Code that handles one entity (a request, a message) gets the same guarantee as a method's own ref parameters from entity.Run: the job's refs stay the entity's values across its own structural changes, and the components in its Writes are carried to the new row when it returns.
public class HitSystem : EcsSystem
{
    [ForEach, Without<Dead>]
    static void Hit(Entity unit, ref Health hp)
    {
        hp.Value -= 10;
        if (hp.Value <= 0) unit.SetDead();   // the row moves to the table with Dead
        hp.Value = Math.Max(hp.Value, 0);    // still the entity's Health: carried over to the new row
    }
}

The details, and why a ref must never cross an await, are in ref and await.

Passes that freeze the structure

Some passes hold refs or spans into the tables for longer than one call, so they freeze the world's structure while they run, and a change throws InvalidOperationException instead of tearing rows:

  • batch methods (Span<T> parameters) and ForEachBatch jobs;
  • jobs that implement INoStructuralChanges, including the ones the generator writes for methods that take no Entity or World;
  • parallel methods, ForEachParallel / ForEachEntityParallel and parallel stages.

The analyzer reports a structural change in a method that promised none (EECS013) and one made from another thread (EECS014).

Keeping tables dense

Tables stay dense on their own. Outside a pass, the table's last row fills a destroyed entity's row at once. Inside a pass, a row that leaves becomes a tombstone the pass skips, and the tombstones are closed when the last pass ends, also when a job throws. A query enumerator abandoned without Dispose (a foreach always disposes it) leaves its pass open until the next Update(), which closes it. There is nothing to call and nothing to monitor.

Many entities at once

For changes to whole sets of entities, the bulk forms take the structural gate once:

var wave = new Entity[1_000];
world.CreateEntities(wave, new Position(0, 0), new Lifetime(60));
int expired = world.DestroyEntities<Lifetime>(QueryFilter.Create().With<Dead>());

SetAll, RemoveAll, DisableAll and EnableAll change a component on every match a whole 64-row word at a time: Bulk changes.

Entities created one at a time (a start-up that loads them, a loop that builds each from data) grow their table by doubling. Reserve it first: EnsureCapacity<T1, …, Tn>(count) grows the table of exactly those components and the entity storage once, to what the loop needs, so the next count creations with those components grow nothing:

world.EnsureCapacity<Position, Lifetime>(100_000);
for (int i = 0; i < 100_000; i++) world.CreateEntity(new Position(i, 0), new Lifetime(60));

CreateEntities reserves on its own. EnsureCapacity(prefab, count) does the same for a prefab's instances (Prefabs), and EnsureEntityCapacity(n) sizes only the entity storage, for entities spread over many tables. Entities that a group puts in another table grow that one.

Full example

A turret that fires every other tick and wears down until it dies: the shots are created and destroyed in the middle of passes, and the Dead tag is set where the death is decided. Put the files in a console project that references EasyEcs (dotnet add package EasyEcs) and run it with dotnet run.

It prints:

tick 1
  Entity 0v1 fires Entity 1v1
  hp 70, shots in flight 1
tick 2
  hp 40, shots in flight 1
tick 3
  Entity 0v1 fires Entity 2v1
  Entity 1v1 expires
  hp 10, shots in flight 1
tick 4
  Entity 0v1 is dead
  hp 0, shots in flight 1
tick 5
  Entity 2v1 expires
  hp 0, shots in flight 0

A shot fired on tick 1 is already counted down by ExpireSystem in the same update, so it expires on tick 3, not 4. On tick 4 the turret is tagged Dead in WearSystem, and FireSystem, which runs next, no longer visits it.

How to use it fast

Instead ofDoWhy
A command buffer played back laterThe change, where it is decidedNo recording, no playback, no allocation
Adding and removing a component each tickA field, or a tag for a state that lasts several ticksA tag the table's mask already has only flips a presence bit
Set(a) then Set(b)Set(a, b)Shorter, the same cost
Creating a known number of entities one by oneCreateEntities, or EnsureCapacity<T1, …, Tn>(count) before the loopOne growth instead of a doubling per full table (EECS031)
A loop of single changes over a filterBulk changes, DestroyEntities<T>(filter)One gate pass, whole 64-row words at once (EECS030)
An Entity parameter the method only readsKeep it read-only (Id, Has, Get)The pass skips structural bookkeeping

10,000 entities whose Health is removed and added back inside a query loop (ToggleComponent), against moving three components out and back in one call each (RemoveMany, 1,000 entities):

CaseMeanvs baselineAllocated
ToggleComponent158 μs13×0 B
RemoveMany51.0 μs4.0×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

Structural changes found while iterating, 100,000 units: per operation some lose their health, one pass marks those at zero as fallen (adds a tag) and a second revives them (removes it). EasyEcs changes structure directly; Friflo, Arch and DefaultEcs record into their command buffers and play them back after each pass:

Mark and revive 1,000 of 100,000 units during iteration

  • EasyEcs
  • Other libraries
EasyEcs: Direct0 B allocated163 μsFriflo.Engine.ECS: CommandBuffer1.12× · 0 B allocated183 μsArch: CommandBuffer6.9× · 448 KB allocated1.12 msDefaultEcs: CommandRecorder79× · 0 B allocated12.9 ms0.00 ns2.00 ms4.00 ms6.00 ms8.00 ms10.0 ms12.0 msTime (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
EasyEcsDirect163 μs1.00×0 B
Friflo.Engine.ECSCommandBuffer183 μs1.12×0 B
ArchCommandBuffer1.12 ms6.9×448 KB
DefaultEcsCommandRecorder12.9 ms79×0 B

The comparison with 10 changes per pass: Comparison.

What it costs

  • A pass that may change structure checks one storage version per entity, so it notices changes; a method that cannot change structure skips even that.
  • Removing a component and adding it back: one presence bit. Gaining a component the table has no column for: one row copy, once per new combination (the move plan is cached).
  • Destroying: O(components); the hole is filled at once outside a pass, or closed when the last pass ends.
  • Growing: a full table doubles, copying its rows; a reservation (EnsureCapacity, CreateEntities) grows it once, to the rows it needs.
  • No allocation after warm-up: there is no buffer to grow.

Pitfalls

MistakeWhat happensCaught by
A change through a component's link in a method with no Entity or WorldThe pass keeps refs into moved rowsEECS013
A change in a batch methodInvalidOperationException: the spans point into the tablesEECS013, and at run time
A change in a parallel methodInvalidOperationException: the structure is frozen while chunks runEECS010, and at run time
A change from another threadRaces with the owner threadEECS014
INoStructuralChanges on a job that changes structureInvalidOperationException at the changeAt run time
A ref from Get<T>() used after a changeIt may point at a stale copy or another entity's rowCode review: get it again
Expecting a new entity in the pass that created itIt is visited by the next passBy design
World.Update() inside a systemThe system runs again inside its own run, until the stack overflowsEECS034
Update() while a query of the same world iteratesUndefined order of passesCode review
Edit on GitHub

Last updated on

How is this guide?

On this page