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>(); // 1Adding 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.
Refs across a change
- The method's own
refparameters 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.inparameters keep showing the values from before the change. - Any other
ref(fromentity.Get<T>(), aQueryitem, 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
refparameters fromentity.Run: the job's refs stay the entity's values across its own structural changes, and the components in itsWritesare 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) andForEachBatchjobs; - jobs that implement
INoStructuralChanges, including the ones the generator writes for methods that take noEntityorWorld; - parallel methods,
ForEachParallel/ForEachEntityParalleland parallel stages.
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));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 0A 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 of | Do | Why |
|---|---|---|
| A command buffer played back later | The change, where it is decided | No recording, no playback, no allocation |
| Adding and removing a component each tick | A field, or a tag for a state that lasts several ticks | A 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 one | CreateEntities, or EnsureCapacity<T1, …, Tn>(count) before the loop | One growth instead of a doubling per full table (EECS031) |
| A loop of single changes over a filter | Bulk changes, DestroyEntities<T>(filter) | One gate pass, whole 64-row words at once (EECS030) |
An Entity parameter the method only reads | Keep 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):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| ToggleComponent | 158 μs | 13× | 0 B |
| RemoveMany | 51.0 μs | 4.0× | 0 B |
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
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 | Direct | 163 μs | 1.00× | 0 B |
| Friflo.Engine.ECS | CommandBuffer | 183 μs | 1.12× | 0 B |
| Arch | CommandBuffer | 1.12 ms | 6.9× | 448 KB |
| DefaultEcs | CommandRecorder | 12.9 ms | 79× | 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
| Mistake | What happens | Caught by |
|---|---|---|
A change through a component's link in a method with no Entity or World | The pass keeps refs into moved rows | EECS013 |
| A change in a batch method | InvalidOperationException: the spans point into the tables | EECS013, and at run time |
| A change in a parallel method | InvalidOperationException: the structure is frozen while chunks run | EECS010, and at run time |
| A change from another thread | Races with the owner thread | EECS014 |
INoStructuralChanges on a job that changes structure | InvalidOperationException at the change | At run time |
A ref from Get<T>() used after a change | It may point at a stale copy or another entity's row | Code review: get it again |
| Expecting a new entity in the pass that created it | It is visited by the next pass | By design |
World.Update() inside a system | The system runs again inside its own run, until the stack overflows | EECS034 |
Update() while a query of the same world iterates | Undefined order of passes | Code review |
Related
Last updated on
How is this guide?
Singletons
World-level state in EasyEcs: one struct value per world for the clock, configuration, counters or a grid, with [ForEach] parameters and SingletonRef handles.
Bulk changes
Set, remove, disable or enable one component on every entity a filter selects in one pass, for round resets, zone-wide statuses and waves, with 0 B allocated.