Design decisions
Every non-obvious design choice of EasyEcs: what was decided, why, what was weighed against it, and the BenchmarkDotNet numbers that settled it.
Why EasyEcs is the way it is: each record states what was decided, why, and what was weighed against it (with the BenchmarkDotNet numbers where a measurement decided). A record is rewritten when the decision changes; a dropped feature stays here with its reason, so it is not proposed again without new facts.
The numbers in these records are the measurements that decided each question, taken with BenchmarkDotNet before and after the change on the machine of the time; they are history, not the current results. Current numbers are on Performance and Comparison. What is planned next is on the roadmap.
| # | Decision |
|---|---|
| D1 | State changes are data: no events or callbacks |
| D2 | Structural changes apply at once: no command buffers |
| D3 | No command buffer for parallel jobs |
| D4 | No Added<T> filter |
| D5 | Order systems by dependencies, not priorities |
| D6 | Removing a component keeps the row |
| D7 | Contiguous columns, not pages |
| D8 | No whole-entity disable |
| D9 | Saves are built in, with Nino |
| D10 | MoveEntities copies rows without encoding |
| D11 | Ids in a prefab name its members |
| D12 | Target policies are opt-in, per index |
| D13 | One owner thread per world |
| D14 | No shared components |
| D15 | .NET 10 only |
| D16 | No partial: generated code lives outside the user's type |
| D17 | Unloading removes types from worlds; bits are reused |
| D18 | No interceptors for query calls; filters carry no references |
| D19 | No settable tag properties |
| D20 | Generic systems register the closed types their assembly names |
| D21 | .NET 10 features only where they measure |
| D22 | Parallel runs use the thread pool and wake helpers only when they pay |
| D23 | Change summaries per block; removals summarized apart |
| D24 | An index's key holds its entities in one array |
| D25 | Structural row loops are compiled for tables without tombstones |
| D26 | Generated members where code would repeat a type, and a suggestion to use them |
| D27 | Reading a missing singleton throws everywhere |
| D28 | Reservations grow to what they need; entity storage on the pinned heap |
| D29 | Performance rules only where the cost is measured and the fix does the same |
| D30 | Saves record types by Nino type id; Nino writes the unmanaged components marked [NinoType] |
| D31 | A record of what persists: a component set to save, loading onto existing entities |
| D32 | The lists of dead buffers are pooled per thread |
| D33 | One entity runs a pass's job: entity.Run |
| D34 | Group filters through interfaces |
| D35 | A record can load without counting as a change |
| D36 | Not added: parallel batch jobs, a row's last write tick, public access sets, a shared parallelism budget |
| D37 | The EasyEcs package brings Nino's generator |
| D38 | The hidden columns are not generic over their component |
| D39 | A whole load can leave the change ticks alone, and a system can start now |
D1. State changes are data: no events or callbacks
Decision. Nothing calls user code when a component is added, removed or written. A change that others react to is
a component (a Dead tag, a message entity) or a tracked write ([Changed<T>], [Removed<T>]).
Why. A callback runs inside another system: the control flow is hidden, it can re-enter the code that raised it, and the scheduler cannot see what it reads and writes, so systems could not run in parallel safely. As data, the order of effects is the schedule's, the generator knows every access, and tests and snapshots see the "events".
Considered. Component events (Friflo, Arch, DefaultEcs); EasyEcs had them once and removed them.
D2. Structural changes apply at once: no command buffers
Decision. Adding, removing, creating and destroying take effect immediately, also in the middle of a query: removed rows become tombstones while a pass runs, the world closes them when the last pass ends, and a pass never sees rows shift under it.
Why. A deferred change is a second, later version of the world that every reader must reason about; an immediate one reads as it is written. The tombstones cost one id check per visited row and nothing outside passes.
Considered. Command buffers played back after the query (Friflo, Arch, DefaultEcs).
D3. No command buffer for parallel jobs
Decision. Parallel [ForEach] methods and parallel stages change no structure (EECS010). A parallel job writes
data; a system after it, on the owner thread, makes the structural change from that data:
public record struct Poison(int DamagePerTick) : IComponent;
public class PoisonSystem : EcsSystem
{
[ForEach(Parallel = true)] // data, on every core
static void Hurt(ref Health hp, in Poison poison) => hp.Value -= poison.DamagePerTick;
}
[UpdateAfter<PoisonSystem>]
public class DeathSystem : EcsSystem
{
[ForEach, Without<Dead>] // structure, after it, on the owner thread
static void Die(Entity entity, in Health hp) { if (hp.Value <= 0) entity.SetDead(); }
}Why. Per-thread recorders would bring back D2's deferred second path, with an order between threads to define and
a playback whose cost hides behind the stage. The pattern above uses the schedule the user already reads, and
bulk changes (SetAll, RemoveAll) make the follow-up pass cheap.
Considered. Per-thread command buffers played back when the stage ends (on the 4.1 roadmap, dropped before implementation).
D4. No Added<T> filter
Decision. There is no filter for "gained T since a tick". [Changed<T>] already selects rows that gained T
(adding stamps the tick, as a write does). When a system must tell a new component from a written one, the creator adds
a tag that the reacting system removes:
public struct Spawned : IComponent; // a tag: "new since the last Greet"
public class GreetSystem : EcsSystem
{
[ForEach, With<Spawned>, With<Health>]
static void Greet(Entity entity) => entity.RemoveSpawned(); // first-time work, then a bit flip
}world.CreateEntity(new Health(100), new Spawned()); // the creator says it is newWhy. A tag is explicit, queryable, saved with the world and costs one presence bit flip. A built-in filter would need a second change tick per tracked row (8 bytes more per row, one more store on every add) and a second companion column per component type, for a need the tag covers.
Considered. Bevy's Added<T>, DefaultEcs' WhenAdded (on the 4.1 roadmap, dropped before implementation).
D5. Order systems by dependencies, not priorities
Decision. Systems run in registration order. [UpdateBefore<T>] / [UpdateAfter<T>] move only the system that
declares them, within its group. Stages come from the ordering graph and the read/write sets: two systems run together
when neither is ordered before the other and their access does not conflict. A cycle throws in AddSystem (the world
stays unchanged) and is reported by the analyzer when it can see it (EECS019); an ordering across groups does nothing
(EECS020). Priority was removed.
Why. Integer priorities from several assemblies collide and say nothing about why a system runs where it does; an ordering names the dependency. Keeping both would give two mechanisms for one job. Moving only the declaring system keeps the registration order of everything else, so adding one ordering never reshuffles unrelated systems.
Considered. Priorities alongside orderings (rejected: overlap); a lexicographic topological sort (rejected: it reordered unrelated systems). Tick time unchanged: ParallelSystems 292-345 μs before, 278-325 μs after, over four runs; WorldSimulation 1,774 μs before, 1,731 μs after.
D6. Removing a component keeps the row
Decision. A removal clears the row's presence bit in its column; only adding a component the table has no column for moves the row.
Why. States that come and go (stunned, burning, dead) then cost a bit flip after the first time, queries test 64
rows per word, and [Removed<T>] is a row like any other (its tick says when).
Considered. Moving the row on every removal (the classic archetype model): a copy per state change.
D7. Contiguous columns, not pages
Decision. Columns are contiguous arrays.
Why. Paged columns iterate at the same speed but add an indirection to every handle access; all they save is the
copy when a table grows, which InitialEntityCapacity and EnsureCapacity remove.
D8. No whole-entity disable
Decision. There is no "disabled entity" that queries skip by default. A tag and Without<T> do it explicitly;
Disable<T>() keeps one component's value while hiding it:
public struct Inactive : IComponent; // the whole entity is off
public struct Bullet : IComponent;
public class BulletSystem : EcsSystem
{
[ForEach, With<Bullet>, Without<Inactive>] // the systems that skip it say so
static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y);
}var bullet = world.CreateEntity(new Bullet(), new Position(0, 0), new Velocity(4, 0));
bullet.SetInactive(); // back to the pool: a bit flip, no row moves
bullet.SetPosition(10, 20).RemoveInactive(); // reused
int pooled = world.Count<Bullet>(QueryFilter.Create().With<Inactive>()); // saves, cleanup, stats see everythingUses: object pools (bullets, effects), players kept in memory while they reconnect, zones without players whose NPCs sleep.
Why. Excluding by default would make every query depend on a state it does not name: a save, a cleanup or a count that must see every entity has to remember to opt back in, and forgetting it fails silently. The tag is data the generator and the reader both see, as the ECS principles ask.
Considered. Friflo (entity.Enabled = false: a hidden tag in the archetype, queries skip it unless
WithDisabled()); DefaultEcs (entity.Disable(): the entity leaves every entity set). Performance by case:
| Friflo | DefaultEcs | EasyEcs | |
|---|---|---|---|
| Switching an entity off or on | moves its row to another archetype | updates every set | flips a presence bit (after the first time) |
| Iterating past disabled entities | skips their archetype | they are in no set | free while a table has none (counts, no bits read); 64 rows per test when mixed |
Pools and effects switch often, where a bit flip beats a row move. Only many entities disabled for long, mixed with
enabled ones in one table, cost EasyEcs a word test per 64 rows that Friflo skips; GroupBy on a sleeping state
splits them into their own tables when that matters. A filter on a system group ([Without<Inactive>] on its
ISystemGroup struct) joins every [ForEach] of the group's systems, so the filter is written once.
100 of 100,000 units fall asleep, the previous 100 wake up, the awake ones are summed
- 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 | Tag | 42.4 μs | 1.00× | 0 B |
| EasyEcs | DisableComponent | 41.4 μs | 0.98× | 0 B |
| Friflo.Engine.ECS | Enabled | 45.9 μs | 1.08× | 0 B |
| Arch | Tag | 82.8 μs | 1.95× | 0 B |
| DefaultEcs | Disable | 103 μs | 2.42× | 0 B |
D9. Saves are built in, with Nino
Decision. World.Save / Load and SaveEntities / LoadEntities write tables, with Nino for managed values.
Unmanaged rows are written in a canonical layout with a hash of their fields, so a changed struct is detected at load;
the generator records where EntityId fields are, so a migration can point them at the new entities.
Why. Rewriting references, loading by type id and reusing rows on repeated loads (0 B allocated) need the
world's tables and the generator; user code over a Query could not do them. (Until 4.0 saving was left to the user.)
D10. MoveEntities copies rows without encoding
Decision. world.MoveEntities(target, ids) copies a group's rows into another world of the thread, rewrites the
ids inside the group and destroys the originals. It shares one core with LoadEntities and prefab groups, which copies
runs of consecutive rows column by column.
Why. It was kept only after measuring that encoding is a real share of a move: 1,000 entities there and back take
150 μs, against 207 μs through SaveEntities + LoadEntities; without a hierarchy one way takes 32 μs against 71 μs.
D11. Ids in a prefab name its members
Decision. An EntityId field in a prefab names a member of its group (member.Id) and is rewritten on every
instance; any other id becomes EntityId.Null. Relations to a world's entities are set after instantiating.
Why. A prefab belongs to no world: an id of a world's entity may equal a member's, so the two cannot be told apart.
D12. Target policies are opt-in, per index
Decision. WhenTargetDestroyed(TargetPolicy.Remove / Destroy) on an EntityId index or a relation index decides
what destroying an entity does to the links to it; Keep is the default (the links stay, findable by the dead id).
ChildOf is Destroy, and may be changed.
Why. Opt-in keeps destroys of worlds without policies as they were. ChildOf's rule is checked inline: through the
generic rule list the cascade benchmark took 650 μs instead of 557 μs; inline, 561-578 μs.
Considered. A marker interface on the component type (rejected: the index must be created generically, which needs
reflection; a call on the index is AOT-safe and per world, like GroupBy<T>()).
D13. One owner thread per world
Decision. A world's systems, queries and structural changes run on its owner thread; parallel stages and parallel
[ForEach] are the only parallelism, and the generator proves them safe. Another thread posts to the owner.
Why. No locks on any hot path; the rules fit in three lines (threading).
D14. No shared components
Decision. No SetSameAs-style shared values. Shared data lives in a singleton, components hold an id into it.
Why. A shared value is a reference that one write changes for many entities, which change tracking and the scheduler could not see.
D15. .NET 10 only
Decision. EasyEcs targets net10.0, no Unity or older runtimes.
Why. It relies on C# 14 extension members, Vector256, pinned object heap columns and current JIT behavior that
older runtimes lack.
D16. No partial: generated code lives outside the user's type
Decision. The generator writes a [ForEach] method's job in a file class of its own and calls the method,
private or not, through [UnsafeAccessor]. A system's update and access set are a SystemCode registered by a module
initializer (held weakly, so a collectible assembly can unload); a runner's entry point is a C# 14 static extension
member of its type. Types the generated code cannot name (a private component, a private runner type) are EECS022.
Why. A system is an ordinary class: no partial on it or on its outer types, nothing generated in its body, so
generated members cannot collide with the user's. UnsafeAccessor compiles to the direct call (the same machine
code, inlined), and the ticks did not move (ForEachSystemWrite, ParallelSystems within noise).
Considered. Partial classes (EECS001 when missing, members injected into the user's type); delegates or function pointers to the methods (an indirect call per row, no inlining); reflection at startup (no AOT).
D17. Unloading removes types from worlds; bits are reused
Decision. world.RemoveTypes(assembly or context) takes an assembly's systems, singletons, indexes, groupings and
components out of the world. Entities stay; tables that had one of its columns are dropped with every cache naming
them. When a collectible context unloads, EasyEcs forgets its save names, and its component bits are reused once no
live world mentions them. A reload keeps data through Save and Load, which map types by id.
Why. Game logic reloaded in a long-running server must leave nothing rooting the old assembly (column arrays,
transition edges, query cache keys, registries), and repeated reloads must not grow every mask. Dropping tables is
the one place a table is deleted outside Dispose, so steady-state code pays nothing (CreateAddDestroy, Prefab and
WorldSimulation within noise).
Considered. Migrating rows from the old types to the new ones in memory (needs a type map for every field; Save
/ Load already map by type id and field hash); never reusing bits (the mask grows by every reloaded component).
D18. No interceptors for query calls; filters carry no references
Decision. Query calls are not intercepted. QueryFilter holds its five sets' first 256 bits inline and its bits
past 255 as an interned id, so it holds no object reference, and its builder copies it once per call.
Why. An interceptor replaces the method a call binds to, but the call's arguments are still evaluated, so a
filter built at the call is built either way; caching a query entry per call site would save only the memo lookup the
call already makes. The cost was the filter itself: five masks with an overflow reference each made every builder
call two copies through BulkMoveWithWriteBarrier and zeroed the caller's frame. Without references, counting 16
entities with QueryFilter.Create().With<Npc>().Without<Dead>().Without<Frozen>() built at the call takes 76 ns
against 124 ns, and with the filter in a static field 24 ns as before (CallSiteBenchmark). Hoisting stays the
advice for hot calls.
Considered. Interceptors with a static filter and a cached entry per site (the arguments make it moot); an analyzer warning for filters built at the call (most calls are cold; the docs teach the static field).
D19. No settable tag properties
Decision. A tag's generated IsX is read-only; SetX() adds the tag and RemoveX() removes it.
Why. entity.IsDead = true (Entitas style) cannot be written where ECS code holds its entities: C# 14 rejects
assigning an extension property of a struct on a foreach variable (CS1654), an indexer result (CS1612) or a field of
an in parameter (CS8332), with a by-value or an in receiver alike. A member that compiles on a local but not in
foreach (var e in hits) or on link.Target teaches the wrong thing; the methods work everywhere, and a structural
change stays a call.
D20. Generic systems register the closed types their assembly names
Decision. A generic system's code is a generic class over the system's type parameters. Its module initializer
registers an instance for each closed type the assembly names (AddSystem<CountOf<Health>>(), new CountOf<Health>(),
a base type CountOf<Health>, and their generic bases), and the code's definition for any other closed type, which
AddSystem closes with MakeGenericType on first use. A generic [ForEach] method of a system stays EECS004.
Why. A module initializer cannot know the type arguments a program will use, and the system class gets nothing generated in it (D16). Closed types named in the system's assembly need no runtime code generation, so Native AOT keeps them; a closed type only another assembly names still works under the JIT. Runners need neither: their entry points are generic, so the caller's type arguments close the job at compile time. A system's own generic method has no caller to give it type arguments.
Considered. Reflection only (breaks Native AOT for every value-type argument, and components are structs); a
virtual generic hook on the system (needs partial or a base class per arity); scanning referenced assemblies for
closed uses (the generated code is file-local to the system's assembly).
D21. .NET 10 features only where they measure
Decision. Of the .NET 10 / C# 14 features weighed for 4.1, each was prototyped and measured with BenchmarkDotNet against the commit before it (two runs each side, 0 bytes allocated throughout), and kept only as a net win:
| Feature | Verdict | Numbers |
|---|---|---|
Vector512 (and Vector<T>) | kept: a table without tombstones counts the set bits of its row words, 8 words per step with AVX-512, else Vector<T> (4 on AVX2, 2 on Arm64) | CountBenchmark, 100,000 rows that must be tested: 48.9-54.5 μs -> 1.21-1.27 μs; Vector<T> alone 2.4 μs, one word at a time 5.2 μs; an indexed lane loop over a Vector512 7.6 μs (unrolled instead) |
GetAlternateLookup on the query cache | kept: probed with the call's bits and a ref to its filter, no key built or copied | a filter past the memo 92-106 ns -> 86-90 ns |
| the memo's ways as structs in one array | kept | a static filter 21.6-21.9 -> 19.0-19.8 ns, no filter 36.8-39.1 -> 35.3-35.5 ns |
[InlineArray] for the memo (every signature's ways inline in one flat array) | dropped | 1-2 ns more (20.3-20.6 / 38.9-39.5 ns), but signature indices are process-wide, so every world holds about 750 bytes per signature of the process (150 KB for 200) and copies it all for each new way |
FrozenDictionary for saved types (lock-free lookups, frozen on the first load after a change) | dropped | a one-entity save and load 2.32-2.33 μs -> 2.23-2.34 μs: within noise; a load resolves each type once, not per entity |
System.Threading.Lock, params ReadOnlySpan, null-conditional assignment | kept | cold paths |
RegisterImplementationSourceOutput | kept: a system's code and the saved-type registration are reached only through module initializers | IDEs skip them while typing |
| C# 14 in generated code | kept: EasyEcs targets net10.0 (default C# 14), so every generator asks for C# 14 and generated lambdas leave out parameter types | |
OverloadResolutionPriority, field | no place: they change overload choice and syntax, not the IL; the API has no array and span overloads of one method, and the candidates' backing fields are written outside their properties | |
first-class span conversions, nameof(List<>) | no place: the remaining .AsSpan() calls are Fill and foreach (ref ...), which conversions do not reach; the generators target netstandard2.0 and compare type names |
Considered. Widening the inline component mask to 512 bits (every filter, key and table mask grows by 32 bytes for components 256-511, which the overflow already covers).
D22. Parallel runs use the thread pool and wake helpers only when they pay
Decision. A parallel [ForEach] and a stage of parallel systems run on the calling thread plus reusable
IThreadPoolWorkItem helpers, in chunks sized by the matching rows. Each job and each stage measures its runs: a run
with helpers yields its time and its items' summed thread time, and helpers stay while they make a run a fifth faster
than its work. Once it runs alone, a probe of four runs with helpers comes after a period that doubles from 16 to
1,024 runs, or at once when runs alone turn 1.5x slower. No spinning, no dedicated threads, no allocation.
Why. Waking a parked pool thread takes from a few to a few hundred microseconds and burns about as much CPU, so a small pass between server ticks ran no faster with helpers and cost twice the CPU. A 60 Hz tick of one 100,000-row pass on a 4-core VM: median pass 123 -> 111 μs, CPU per tick 436 -> 290 μs (serial: 108 μs, 229 μs). BDN: ParallelSystems 804-808 -> 746-768 μs, ParallelForEach 294-308 -> 267-271 μs, BattleServer and Runner unchanged.
Considered.
- A crew of dedicated helper threads that spin about 50 μs after a run: it won only when passes ran back to back (BenchmarkDotNet's loop). In a server tick it lost: median 130 against 135 μs, but p90 170 against 190 μs and CPU per tick 990 against 760 μs.
ThreadPool.UnfairSemaphoreSpinLimit: closes the back-to-back gap, but it is process-wide and keeps pool threads spinning between ticks (49 ms CPU per 16 ms tick), so it stays the application's choice.
D23. Change summaries per block; removals summarized apart
Decision. A tracked column keeps, per 64-row word, one 32-byte entry (latest tick, the rows at it, a bound of the
others, and a bound of the ticks of rows lacking the component), and per 4,096-row block the words at the block's
latest tick as a bit mask with a bound for the rest. A Changed<T> pass finds the next written word with one bit
scan; a Removed<T> pass skips words by their removal bound and blocks by their own removal summaries, so writes of
T do not make it visit their words.
Why. BDN against the per-word summaries: RemovalComparison with 10 removals 1.07-1.09 -> 0.87 μs; ChangeTracking
Changed, 10 written, 609-650 -> 514 ns; ChangeTrackingComparison 612-636 -> 497-573 ns. BattleServer,
WorldSimulation and the 1,000-written cases are unchanged.
What remains. Friflo reports 10 removals in 0.70 μs: it collects the removed ids in a callback as they happen, so reading them costs nothing extra. EasyEcs keeps removals as data (D1): its pass costs about 90 ns plus about 30 ns per word with a removal, the loads of the summaries and rows. At 1,000 removals the two are even (71 against 73 μs).
Considered. Interleaving a word's summaries with its block's (no gain: the summaries of 100,000 rows fit in L2); noting the word in a separate helper called per row (slower: 600 μs per query tick); finding the column and word of a removal once for its stamp and its removal note (no measurable gain, reverted).
D24. An index's key holds its entities in one array
Decision. A value index and a relation index keep each key's entities in one id array (IndexHead). A leaving
entity leaves a hole the key's next entity fills, so entities never move and a loop finds each entity once, whatever
is destroyed during it; arrays of emptied keys are reused. CreateEntities indexes its entities with one key lookup.
Why. The lists linked through per-entity nodes cost one dependent load per entity. BDN: IndexBenchmark 710 -> 156 μs; ValueQueryComparison 648 -> 225 μs (Friflo 323 μs); RelationComparison 26.8 -> 23.4 μs (Friflo 26.5 μs); cascades unchanged, 0 bytes.
D25. Structural row loops are compiled for tables without tombstones
Decision. A [ForEach] that may change structure runs each table through a row loop compiled twice: for a table
with tombstones (each row tests its id) and for one without (no test). A table without tombstones at the call gains
one only through a structural change, which bumps the storage version and ends the loop.
Why. StructuralChangeComparison, 10 of 100,000 units killed per tick: 85.7 -> 80.9 μs (three rounds; Friflo's command buffer 77 μs); 1,000 killed and BattleServer unchanged.
Considered. Holding the storage version seen in a register instead of re-reading it per row: 82 -> 108 μs (the job's call leaves too few callee-saved registers, a column ref spills and round-trips the stack every row).
D26. Generated members where code would repeat a type, and a suggestion to use them
Decision. A query item's components have names: item.Position for item.Component1, generated per Query<…>
shape the code calls. A buffer element has writers on prefabs: prefab.SetLoot(…), on
Prefab.SetBuffer<T>(params ReadOnlySpan<T>). The analyzer suggests the generated member wherever code calls the
generic API (EECS033, Info, with a code fix): entity.Get<Position>() as entity.Position, Has<T>() as HasX or
IsX, Set(new T(…)) as SetX(…), GetSingleton<T>() as world.X, Index<T, TKey>() as world.XIndex,
item.Component1 as item.Position, and the other members the generator writes. Multi-type Disable / Enable and
multi-type bulk calls are not built.
Why.
- Query items.
Component1..nmakes the reader count the type arguments. The named member is an inlined getter over the same ref, so it costs nothing. One file per shape keeps an assembly's output to the shapes it uses; one extension block per component and position would mean 45 blocks per component. - Prefab buffers. Without
SetBuffer, a prefab could hold only an empty buffer: filling one meant copying a buffer value, which EECS012 rejects. A relation gets no prefab writer, because a recipe's links would name the prefab's own rows. - The suggestion. The docs, samples and templates write the generated members, and code that mixes both spellings
reads worse than either. The rewrite is offered only where it means exactly the same call: the member must be
generated for that type in that compilation (checked by binding the replacement), and it must return the same kind
of reference:
Get<T>()of a tracked component, whose property isref readonly, becomesWriteX()(an indexed component has no writer, so itsGet<T>()keeps its spelling). A buffer's members exist only while code namesDynamicBuffer<T>, so the suggestion is not made where the call is the last such name. It is Info: a suggestion in the IDE that does not fail a build, since generic code needs the generic API and the two spellings compile to the same call. The analyzer's operation callback on invocations already runs for EECS025 and EECS034, so the suggestion adds one symbol check per call.
Considered.
Disable<T1..Tn>(),RemoveAll<T1..Tn>()and the other multi-type calls. After a table's first disable, each call flips presence bits in place. n calls cost n gate entries of a few nanoseconds, and a bulk call over several types needs a meaning for "has any of them" that one-type calls do not. Not built.- A warning instead of a suggestion. It would fail builds that treat warnings as errors over spelling alone.
- Rewriting
SingletonRef<T>.Valueasworld.X. ASingletonRef<T>keeps the singleton's slot, so the rewrite would add a lookup per access. Not suggested.
D27. Reading a missing singleton throws everywhere
Decision. Every read of a singleton the world does not have throws InvalidOperationException: world.X,
GetSingleton<T>(), SingletonRef<T>(), and so a [ForEach] method's singleton parameter, on its system's first
run. The message names the singleton and the calls that add it (world.SetClock(...), AddSingleton<Clock>(), or
GetOrAddClock() where a default is meant). GetOrAddSingleton<T>() / GetOrAddX() is the one read that adds the
default, and the code that calls it says so.
Why.
- A forgotten setup fails where it happens. Until 4.2 a
[ForEach]parameter added the default singleton whileworld.Xthrew. A world built without itsSetClock(...)then ran on a clock with no step: entities stood still, a test passed for the wrong reason, and nothing pointed at the missing line. Now the firstUpdate()names the singleton and the call to add. - One rule for every read. The same singleton read in
OnUpdateand taken as a parameter behaved differently; now a read is a read, and only a call namedGetOrAddadds. - Nothing on the hot path. A job resolves its singletons once per pass, when it is built; the check is the null test the old add made, and the throw is a cold method.
Considered.
- Keep adding the default for
[ForEach]parameters. It saves a setup line in small programs and hides the forgotten one in real servers, where the default of most singletons (a clock, a configuration, a spawner) is wrong. - An analyzer rule for a singleton parameter no code adds. The setup is host code, often in another assembly, or
comes from
Load,LoadEntitiesor a plugin; a compile-time check would miss those or flag correct code. - A check in
AddSystem. Systems are often added before their singletons, or before aLoadbrings them; the first run is the earliest point where the singleton has to exist. GetOrAddX()as the explicit default (chosen): where the default is right, such as a counter starting at zero, one call says it.
D28. Reservations grow to what they need; entity storage on the pinned heap
Decision. A reservation grows a table to the rows it needs, rounded up to whole presence words (64 rows), and the
entity storage to the ids it needs, or either to twice its capacity when that is more; not to the next power of two.
The reservations are EnsureCapacity<T1..Tn>(count) (the table of exactly those components), EnsureCapacity(prefab, count), EnsureEntityCapacity, CreateEntities, InitialEntityCapacity and a restore. An entity-storage array of
85,000 bytes or more that a reservation sizes is allocated on the pinned object heap, beside the unmanaged columns; the
steps of a doubling stay on the large object heap.
Why.
- A start-up's cost was a collection, not the creation. In a world that has never held entities, creating 100,000
of them (the setup of Doraku/Ecs.CSharp.Benchmark: a fresh world per invocation, measured once) cost 11.8 to 12.6 ms
in bulk, while the same rows cost 1.2 to 1.6 ms when the arrays were small objects (
DOTNET_GCLOHThresholdraised). .NET starts a full collection once the allocations on the large object heap since the last one pass a budget, and, separately, those on the pinned object heap; after the collection between two iterations that budget is 3 MiB for each (GC.GetGenerationBudgetin the measured call).CreateEntities(new Entity[100_000], ...)put the 1.6 MB handle array and a 2 MB entity array (131,072 records) on the large object heap, 3.7 MB, so every call paid a background gen2 collection; its throttling of large allocations made it cost 5 to 15 ms on the 4-core machine (4.8 ms as a blocking collection,DOTNET_gcConcurrent=0). - Both changes keep it under both budgets. Sizes that a reservation names save 0.6 MB of the 100,000 entities; the entity records on the pinned heap move 1.6 MB to the other budget: the large object heap then holds the handles and the entity rows (2.4 MB), the pinned heap the records and one to three int columns (2.0 to 2.8 MB), and no collection runs. Bulk creation went from 11.8 / 12.6 / 12.6 ms to 2.7 / 2.5 / 2.7 ms (one, two, three components), 5.03 / 5.53 / 6.03 MB to 4.20 / 4.58 / 4.96 MB.
EnsureCapacity<T1..Tn>for entities created one by one.EnsureEntityCapacitysized only the records, so the table still doubled from 64 rows, allocating twice its final size: 2.67 / 3.32 / 3.99 ms and 4.53 / 5.53 / 6.53 MB before, 1.94 / 2.71 / 2.60 ms and 2.67 / 3.05 / 3.44 MB with the table reserved (Friflo withEnsureCapacityon its store and archetype: 11 to 12 ms; Arch withEnsureCapacity: 3.4 to 4.2 ms).- Pinning moves nothing that would have moved. Neither heap compacts by default; handles index the record array
without bounds checks and it is never moved; the collector scans a pinned array's references like any other. The
arrays a doubling discards stay on the large object heap, which can still be compacted when asked to
(
GCSettings.LargeObjectHeapCompactionMode), so they leave no hole for good. - Warm paths are untouched. A world that is not growing runs the same code; reservations add one comparison. Doubling still bounds a table that grows by many small reservations (two batches of 100 and 30 rows: 128, then 256).
Considered.
- Pages for the records and columns (Arch's chunks of 16 KB): small objects never set off a full collection, but every handle access would pay an indirection (D7).
- Every large record array on the pinned heap, doubling steps too: a start-up of 100,000 entities with three components and no reservation then crossed the pinned budget twice (10.0 ms against 6.6 ms).
- The entity rows on the pinned heap as well: the records, rows and two int columns already pass 3 MiB there.
- Returning a disposed world's arrays to a pool for the next world: the records cannot go, since handles of the disposed world still index them unchecked, and the pool would keep memory a process has finished with.
- A count-only
CreateEntities(count, values)without the handle span: not needed once the bulk call stays under both budgets with the span.
D29. Performance rules only where the cost is measured and the fix does the same
Decision. The analyzer reports code that works but does more than it needs, as EECS025 to EECS034, and the severity says which kind: a warning means the code costs (a benchmark shows it slower than its fix, or allocating); a suggestion (Info) means the fix is the same cost written shorter; an error means the code cannot work. A rule ships only when its fix does the same thing, and a code fix is offered only when the analyzer has bound the replacement. Candidates without a measured cost, or with a fix that changes behavior, were dropped.
| Rule | Severity | Measured (100,000 entities) |
|---|---|---|
| EECS025 a write access that only reads | Warning | a tracked ref 306 µs, in 271 µs; untracked equal (270 / 276 µs): the cost is the write set |
| EECS026 an unused parameter | Warning | per row equal (41 / 46 µs); an Entity or World makes the system run alone, a ref of a tracked component stamps every row |
| EECS027 a lookup per row | Warning | entity.Read<T>() 258 µs, a parameter 40 µs; Has<T>() 208 µs, Maybe<T> 86 µs; a singleton through the World 105 µs, a parameter 48 µs |
| EECS028 an allocation every update | Warning | garbage every tick; the Don't list |
EECS029 an instance [ForEach] method | Warning | instance 104 µs, static 41 µs |
| EECS030 a structural change per entity over a query | Warning | BulkBenchmark: entity by entity 19.1x the time of SetAll / RemoveAll, about 99x that of DisableAll / EnableAll |
| EECS031 creation one by one in a counted loop | Warning | a fresh world only (D28); MicroBenchmarks.Churn 2.1x the time of ChurnBatch |
| EECS032 counting and testing by hand | Warning | Count() > 0 429 ns, Any() 18.6 ns; a Has<T>() test in the loop 332 µs, a filter 59.5 µs |
| EECS033 the generated member | Info | the same call, the same cost (D26) |
| EECS034 a world update inside a system | Error | recursion, or systems run in the middle of a stage |
AccessBenchmark measures each pair (BenchmarkDotNet, a shared 4-core Xeon at 2.1 GHz, .NET 10.0.13); every variant
allocates nothing.
Why.
- Warnings fail builds that treat warnings as errors, so each must be right wherever it fires. The rules read
every use before they report: EECS025 counts an assignment,
++, areforoutargument, a method that is notreadonly, areflocal and athis refextension as a write; EECS027 reports only lookups made on every row, of components the method does not change itself; EECS028 leaves outthrow,[Conditional]calls, console output, and theOnUpdateof a system with its ownUpdateInterval; EECS030 leaves out aSetthat overwrites a component the query requires and one of a grouped component (its rows move one by one inSetAlltoo); EECS031 leaves out constant counts under 4,096 and arrays created with one (no array reaches the large object heap), loops after a reservation, creations under a branch or in an inner loop, and loops in systems (a running world reuses its rows); EECS032 reportsCountcompared with 0 or 1, a loop that only counts, and a test that is the loop's first statement. - Every cost is a warning, whatever its size. A reservation pays most in a world growing to that size for the
first time, and
Anyand filters in proportion to the rows a loop would visit; where the rules fire, the code is slower than its fix, so they are warnings like the others. Only EECS033 is a suggestion: the generated member calls the generic API, so it changes how long the code is, not what it costs. - The fix is the rule's proof. Each replacement is bound in place before it is offered: a member that is not
generated, a filter that does not compile or a caller that passes
refto the method means no fix.
Considered.
- Several components added or removed one call at a time (
e.Set(a); e.Set(b);ase.Set(a, b)): 500.7 µs one by one against 480.7 µs together, and 290.1 against 308.7 µs for two 16-byte components. The second move is as cheap as the first once the transition is cached. Dropped. - A tag taken as a parameter instead of
[With<T>]: 37.7 against 38.6 µs; what costs is the access it declares, which EECS026 already reports for any unused parameter. [Changed<T>]of an untracked component: the attribute's constraint already fails it (CS0315).Parallel = trueon structural or tiny work: structural work is EECS010; whether a pass is tiny depends on the entity counts at run time.- Conflicts between systems of a parallel stage and redundant orderings: the stages are formed from the order the
host adds systems in, at run time; a redundant
[UpdateAfter<T>]costs nothing. World.Updatefrom another thread: a world may run on any one thread that owns it (one world per thread), and EECS014 reports the structural calls that race with its owner.- Hand-written
Queryloops inOnUpdate,CaptureorDescribeon the hot path, value index lookups in loops:Queryis a supported API whose costs EECS030 and EECS032 already name; a snapshot per tick is how rollback works; an index lookup is O(1) and a[ForEach]method cannot hoist it. No rule. - A
QueryFilterbuilt per call instead of kept in astatic readonlyfield: a filter is a small struct with no references (D18); not measured as a cost. No rule.
D30. Saves record types by Nino type id; Nino writes the unmanaged components marked [NinoType]
Decision. A save (format 2) records each component, buffer element and singleton type by its Nino type id: the
hash Nino computes from the namespace-qualified name, or from the name [NinoFormerName] keeps. A plain unmanaged
component is written as its raw rows, as before; an unmanaged one marked [NinoType] is written by its formatter, row
by row. A load refuses rows written another way than the process writes them, and two types of the process that share
an id, with a message that names the fix. Format 1 saves (4.3 and earlier) are refused.
Why.
- Renames are the change saved data meets most often, and a name in the save made each one a silent loss of data.
Nino already has the rule for it (
[NinoFormerName]keeps a type's id across renames, also for its own polymorphic data), so EasyEcs follows that rule instead of adding a second rename attribute or map. - Unmanaged components need to change too. A raw row can only load into the same shape; a component that will
gain fields says so by marking itself
[NinoType], and its format decides what may change (VersionTolerantappended members,Keyedany member change). Components that stay raw keep the block copy. - The cost stays where it is chosen. 100,000 entities in two raw tables save in 271 µs before and 262 µs after, load in 1,052 and 1,003 µs; one entity of four components goes through bytes and back in 2.25 and 2.22 µs; all 0 B. A type costs four bytes for its id instead of its name.
- No conversion of old saves. A reader for format 1 would keep the name lookup in every later version, for data a build can write again once (the migration guide has the steps).
Considered.
- Names with a rename map (
World.RenameType("Old", typeof(New))): a second mechanism next to Nino's, configured in code instead of on the type. - Nino's type registry for the lookup: it caches types process-wide, so a collectible plugin's types could never unload; EasyEcs computes the ids itself and forgets them with the plugin.
- Every unmanaged component through Nino: the block copy of a column is what makes a save fast, and most components never change shape.
D31. A record of what persists: a component set to save, loading onto existing entities
Decision. SaveEntities(output, ids, set) writes only the components of a ComponentSet, and
LoadEntitiesInto(input, entities) loads a group save onto entities that exist, the i-th saved entity onto the i-th
given, each moving table at most once. A ComponentSet is a bit mask built once (With<T>(), With(Type)); the save
selects each table's rows in O(group).
Why.
- An actor persists part of its entity: a balance survives a restart, its connection and timers do not, and those runtime components often have no Nino formatter. A set names the record per save, so one entity can feed several stores.
- The entity exists before its record arrives. An actor is activated, gets its entity and starts handling
messages while its record loads from a database;
LoadEntitieswould create a second entity and rewrite the record'sEntityIdfields to it. - One move per entity. The components a record brings are added with one transition (a signature cached per
table), then written, so the indexes, groups and change ticks follow as with one
Setof all of them. - Measured (
MigrationBenchmark, warm, 0 B): saving two of an entity's four components takes 104 ns, loading them onto an entity that holds the other two 722 ns, against 2.22 µs to send the whole entity through bytes and create it again.
Considered.
- A
[Persistent]attribute on component types: one global choice, where different saves of one entity need different components. - Filtering at load time: the save would still write, and need formatters for, the runtime components.
LoadEntities, then copying the components onto the actor by hand: two moves per entity, a temporary entity, andEntityIdfields that name the temporary one.
D32. The lists of dead buffers are pooled per thread
Decision. A DynamicBuffer<T> whose value dies (its component removed, its entity destroyed, its table dropped,
a disabled value discarded) empties its list and keeps it in a pool of its element type on the current thread; a first
write takes a list from there before allocating one. The pool holds only lists that died while none were taken, and
drops a list of more than 4 KB.
Why.
- Entities that come and go with buffers allocated per entity. An actor loading with a mailbox and unloading
again cost two allocations each time: 1,000 actors with four messages each, unloaded and loaded,
took 76.4 µs and 85.9 KB before, 76.9 µs and 0 B after (
BufferChurnBenchmark); the other buffer benchmarks did not move. - Per thread is per world. Buffers die in structural changes, which run on the world's owner thread, so the lists of a world come back to the buffers of that world (or another world of the thread) with no lock.
- Bounded like the rows. The pool grows only to the most lists dead at once, the peak a table's capacity keeps as well, and the 4 KB cap leaves a list that once grew large to the collector.
Considered.
- Recycling when rows are released: a row move copies the reference first, so the list would still be in use.
- A fixed number of pooled lists (256): churn above it allocated again, and a peak is already bounded by the entities that held the lists.
D33. One entity runs a pass's job: entity.Run
Decision. entity.Run<T1..Tn, TJob>(ref job) and Run(ref job, filter) run an IForEachEntity job on one
entity with what a pass guarantees: Writes stamp change ticks, the refs stay valid across the job's own structural
changes (written components are carried to the new row, also when the job throws), INoStructuralChanges freezes
the structure. The filter is tested on the row itself.
Why.
- Code that handles one entity at a time (a request, an actor's message) otherwise looks each component up through the handle and takes its refs again after every structural change. One job gets one lookup for all its components and the same rules as the systems.
- No slower than the code it replaces. 1,000 calls on 10,000 entities with 1, 3 or 5 components, with and without
a filter and a structural change, against the same work through the handle (
SingleEntityBenchmark): 0.69 to 1.06 times the handwritten time, 0 B. The cases at 1.04 and 1.06 (a filter and a structural change, 3 and 5 components) are within the run's error. - The thread rule stays the owner's. A plain flag store freezes the structure when the gate is free (the owner
outside any region); inside a parallel region the region's freeze is already held, and the analyzer reports
Runas a structural call (EECS010, EECS013, EECS014).
Considered.
- A filter tested through the query cache: a lookup of the filter's table set per call, which cost more than the job; testing the row's table mask and presence bits is O(1) per filter component.
- Interlocked freeze and pass counters, as passes use: about 12 ns per call; the owner thread alone touches them when the gate is free.
D34. Group filters through interfaces
Decision. A system group that implements IGroupWith<T> or IGroupWithout<T>, itself or through one of its
interfaces, gets the same filter as [With<T>] / [Without<T>] on the group. The generator reads the interfaces with
the attributes; nothing changes at run time.
Why.
- A generic group cannot name its filter in an attribute. C# refuses a type parameter as the type argument of an
attribute (CS8968), so
[With<Inbox<TActor>>]cannot sit onIActorGroup<TActor>. Interfaces take type parameters, and one interface then gives every actor type a group of its own. - The same filter, the same cost. The interfaces become the same
With/Withoutof every[ForEach]method of the group, built once per method; a pass does not know where they came from. - Types from another assembly work. A framework can ship the tag and the interface; the closed types are the
user's (
struct Map : IActor<Map>filters byIn<Map>).
Considered.
- A
Typeargument in the attribute ([GroupWith(typeof(Inbox<>))]closed over the group): attributes cannot take open generic types bound to the group's arguments either, and the binding rule would be ours to invent. - Filters in a static member of the group: the generator would have to evaluate code; interfaces are symbols.
D35. A record can load without counting as a change
Decision. LoadEntitiesInto(input, entities, markWritten: false) loads the record without stamping it: every
component the record holds ends with tick 0 (never written), whether it replaces a value or adds one; the components
it does not hold keep their ticks. The default stays true.
Why.
- A restored record is not news. A system that saves or replicates
[Changed<T>]rows would otherwise send what was just read from the database straight back. - A replaced value's tick describes a value that is gone. Keeping it would make a default from a prefab count as written, so every activation of an actor made from its prefab would save the record it just read.
- The load already decides the ticks (one move per entity, then the values); clearing them costs nothing.
Considered.
- Keeping the tick of a replaced value: restored actors would need a second prefab per kind, one without the persistent components.
- Clearing the row's ticks after the load: components the record does not hold would lose their writes too.
- A separate
RestoreEntitiesInto: the same call with one difference; a parameter says it where it is used.
D36. Not added: parallel batch jobs, a row's last write tick, public access sets, a shared parallelism budget
Decision. Four requests were weighed and left out.
Why.
- Parallel batch jobs (
ForEachBatchParallel,[ForEach(Parallel = true)]on span methods). 100,000 entities,ParallelForEachBenchmark: a heavy steering pass took 766 µs as a parallel batch and 727 µs per entity in parallel; a light drift took 54.5 µs and 55.6 µs (107 µs on one thread). On several threads the per-entity pass already reaches memory's speed, so the batch form added an API, a job type and generator paths for no gain. entity.LastWriteTick<T>().entity.Run(ref job, QueryFilter.Create().Changed<T>(tick))answers "was it written since?" for one entity without exposing the tick column.- Public
SystemAccess. The read and write sets are how the scheduler decides; publishing them freezes that shape into the API, and no use outside the scheduler remained. - One parallelism budget for several worlds. The host sets
WorldOptions.MaxDegreeOfParallelismper world; a shared budget would be state shared across worlds, which each belong to one owner thread.
D37. The EasyEcs package brings Nino's generator
Decision. EasyEcs references the Nino package (runtime and generator) instead of Nino.Serialization (runtime
only). Nino.Generator ships its analyzer through buildTransitive, so every project that references EasyEcs gets
the formatters of its [NinoType] components without a package of its own.
Why.
- One package to install. Saves are built in; a managed component needed a second reference, at the same version
as the Nino of EasyEcs, or
Savethrew at run time. - No drift. The generator always matches the runtime EasyEcs was built with; an older explicit reference fails
restore with
NU1605instead of compiling against another Nino. - Little cost. In a project without
[NinoType]types the generator writes one empty internal registry.
Considered.
- Keeping
Nino.Serializationand documenting the second reference: the step users missed. - Bundling Nino's generator inside the EasyEcs package: a copy of another project's analyzer to keep in sync by hand.
D38. The hidden columns are not generic over their component
Decision. The change-tick column of a tracked component and the tag of a disabled one are non-generic types
(ChangeTick, DisabledTag), one bit per owner, each described by its owner's Type (released with it when its
context unloads). The public Disabled<T> stays: its bit is the tag bit of T.
Why.
- Native AOT without warnings. Registering
ChangeTicks<T>through the same generic path as a component made the AOT compiler seeChangeTicks<ChangeTicks<...>>(andDisabled<Disabled<...>>) without end: IL3054 in every program with a tracked component, the built-inChildOfincluded, which fails a build with warnings as errors. - Nothing changes at run time. A tick column was already 8-byte unmanaged rows found by a bit; the bit now comes from a static field of the component's own registration.
Considered.
- Suppressing IL3054 in the package: a warning in users' builds cannot be suppressed from a library, and the recursion is real for the compiler.
- A separate tick array per table outside the columns: a second storage path for moves, snapshots and saves.
D39. A whole load can leave the change ticks alone, and a system can start now
Decision. world.Load(input, markWritten: false) clears the change ticks of every loaded row (no write, no
removal), as LoadEntitiesInto(..., markWritten: false) does for a record. AddSystem(system, changesFromNow: true)
sets the new system's last run to the current tick and moves the world's tick on, so its first run sees only later
writes. Both defaults stay as they were.
Why.
- A restart is not news. A process that resumes a saved world would otherwise save or replicate everything on the
first tick of every
[Changed<T>]system. - Systems added after the load need nothing more. A new system's first run looks at ticks from 1; cleared rows have tick 0.
changesFromNowcovers the other case: a system switched on in a world whose rows were written by code (or a default load), which should not treat that history as changes.
Considered.
- Only
changesFromNow: systems that already ran before the load would still see every loaded row. - Setting the last run without moving the tick: writes made later in the same tick would be missed.
Related
Last updated on
How is this guide?
Using EasyEcs with AI assistants
Give Claude, ChatGPT, Cursor or Copilot the EasyEcs docs: llms.txt, a Markdown copy of every page, and a rules file for AGENTS.md, CLAUDE.md or Cursor.
Roadmap
What is planned for EasyEcs, how each change is proven, and the features that were weighed and dropped, with links to the decisions.