# EasyEcs 4.6 documentation > EasyEcs is an open-source, high-performance archetype Entity Component System (ECS) for C# and .NET 10 servers, built for speed first and zero allocation second. Components are plain structs stored in archetype tables with 64-byte-aligned columns; systems are [ForEach] methods that a Roslyn source generator compiles into JIT-inlined struct jobs, and an analyzer with code fixes reports ECS design mistakes and avoidable costs at compile time. Structural changes apply immediately, even in the middle of a pass, with no command buffer, and after warm-up updates, queries and structural changes allocate nothing. Change tracking, removal detection, prefabs, capacity reservation before spawn waves (EnsureCapacity), dynamic buffers, value indexes, relations and hierarchies, parallel systems, snapshots, saves and entity migration are built in. It targets net10.0 only (no Unity) and is built for game servers, simulations and other long-running real-time backends. MIT licensed, installed from NuGet as EasyEcs. # EasyEcs documentation > Start here. What EasyEcs is, how to install it, a first system in a dozen lines, and the order to read the guide in. URL: https://ecs.xgamedev.net/en/docs Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs.md **EasyEcs is an open-source, allocation-free archetype Entity Component System (ECS) for C# and .NET 10 servers.** You write plain data and `[ForEach]` methods. A source generator turns them into inlined struct jobs, an analyzer catches design mistakes at compile time, and a full server tick of 100,000 entities takes 1.72 ms and allocates 0 B. New to the pattern itself? Read [What is an ECS?](https://ecs.xgamedev.net/en/docs/what-is-ecs) first. - Save 10,000 entities and load them back, vs DefaultEcs: **30× faster**, EasyEcs 146 μs, DefaultEcs 4.33 ms - Head-to-head benchmarks it is faster in: **24 / 37**, against Friflo.Engine.ECS, Arch and DefaultEcs - One server tick: **1.72 ms**, 100,000 entities in one world - Allocated per tick: **0 B**, after warm-up BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Install ```bash dotnet add package EasyEcs ``` The package targets `net10.0` and brings the source generator, the analyzer and its code fixes with it. There is nothing to register. ## A first system ```csharp using EasyEcs; using var world = new World(); world.AddSystem(); world.CreateEntity(new Position(0, 0), new Velocity(1, 0)); world.Update(); // Position is now (1, 0) public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; public class MovementSystem : EcsSystem { [ForEach] static void Move(ref Position p, in Velocity v) => p = new(p.X + v.X, p.Y + v.Y); } ``` `ref` marks what the system writes and `in` what it only reads. The generator reads those two words to build the loop, to decide which systems may run in parallel, and to tell [change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking) which rows were written. ## Where to start - [What is an ECS?](https://ecs.xgamedev.net/en/docs/what-is-ecs): Entities, components and systems, archetype and sparse-set storage, and when an ECS fits. - [Features](https://ecs.xgamedev.net/en/docs/features): Every feature on one page: what it does, when to use it, what it costs. - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): Build a small simulation step by step, from the world to the update loop. - [Example: a battle server](https://ecs.xgamedev.net/en/docs/example): Every feature in one world: the code of the battle server benchmark. ## Reading order ```mermaid flowchart LR W[What is an ECS?] --> F[Features] --> G[Getting started] --> P[ECS principles] --> X[Example] X --> U[Guide] --> R[Reference] U --> Perf[Performance] --> A[Architecture] F --> C[Compare] ``` ## Guide The guide has one page per concept, in the order you need them. - [Structuring a real project](https://ecs.xgamedev.net/en/docs/guide/project-structure): Where components, systems, the host loop and the tests go, as `dotnet new easyecs` lays them out. - [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components): Handles, ids, tags and the generated members. - [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries): `Query`, `Count`, `Any`, `QueryFilter`, struct jobs and `entity.Run` on one entity. - [Systems](https://ecs.xgamedev.net/en/docs/guide/systems): `[ForEach]` methods, ordering, groups, cadence and errors. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): Visit only the rows written or removed since a system last ran. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): One owner thread per world, parallel systems and parallel `[ForEach]`. - [Common mistakes](https://ecs.xgamedev.net/en/docs/guide/common-mistakes): What goes wrong first, and the rule or analyzer error that catches it. The rest of the guide covers singletons, structural changes, `ref` and `await`, dynamic buffers, indexes and relations, hierarchies, groups, cleanup and disable, [prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs), bulk changes, snapshots, saves, migration and unloading, [hosting](https://ecs.xgamedev.net/en/docs/guide/hosting), [testing](https://ecs.xgamedev.net/en/docs/guide/testing), [debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics), [troubleshooting](https://ecs.xgamedev.net/en/docs/guide/troubleshooting), and every [analyzer rule](https://ecs.xgamedev.net/en/docs/guide/analyzer). ## Compare - [Performance](https://ecs.xgamedev.net/en/docs/performance): Which API to use when, do's and don'ts, the benchmarks and how to measure. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): EasyEcs against Friflo.Engine.ECS, Arch and DefaultEcs, feature by feature and measured. Coming from another ECS? See EasyEcs against [Arch](https://ecs.xgamedev.net/en/docs/vs-arch), [Friflo](https://ecs.xgamedev.net/en/docs/vs-friflo), [DefaultEcs](https://ecs.xgamedev.net/en/docs/vs-defaultecs) and [Unity Entities](https://ecs.xgamedev.net/en/docs/vs-unity-entities), and the migration pages for [Arch](https://ecs.xgamedev.net/en/docs/migrate-from-arch), [Friflo](https://ecs.xgamedev.net/en/docs/migrate-from-friflo) and [DefaultEcs](https://ecs.xgamedev.net/en/docs/migrate-from-defaultecs). ## Reference - [API reference](https://ecs.xgamedev.net/en/docs/reference): Every public type and member, generated from the source. - [API and complexity](https://ecs.xgamedev.net/en/docs/api): Every public API with its complexity. - [Architecture](https://ecs.xgamedev.net/en/docs/architecture): Storage, entity lifecycle, the query cache, systems, generators and threads. - [FAQ](https://ecs.xgamedev.net/en/docs/faq): Production use, allocations, threads, Unity, saves, hot reload, Native AOT. - [AI assistants](https://ecs.xgamedev.net/en/docs/ai): `llms.txt`, Markdown copies and a rules file for your project. - [Changelog](https://ecs.xgamedev.net/en/docs/changelog): What changed in each release. Why it is built this way: the [design decisions](https://ecs.xgamedev.net/en/docs/decisions); what comes next: the [roadmap](https://ecs.xgamedev.net/en/docs/roadmap). Upgrading from an earlier version? The [migration guide](https://ecs.xgamedev.net/en/docs/migration) covers every step from v2 to v3, v3 to v4 and between the 4.x releases. --- # What is an ECS? > An Entity Component System (ECS) splits a program into entities, components and systems: how storage works, archetypes vs sparse sets, ECS vs OOP, C# libraries. URL: https://ecs.xgamedev.net/en/docs/what-is-ecs Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/what-is-ecs.md An **Entity Component System (ECS)** is a way to structure a program around its data. An **entity** is an id, a **component** is a piece of plain data attached to an entity, and a **system** is logic that runs over every entity that has a given set of components. Behaviour comes from which components an entity has, not from which class it is an instance of. The pattern comes from game development, where a world holds thousands of things that share some traits and differ in others, and every one of them must be updated many times a second. It fits any program with the same shape: game servers, simulations, digital twins, agent models. In C# and .NET an ECS comes as a library. EasyEcs, Friflo.Engine.ECS, Arch and DefaultEcs are .NET libraries (the last three also run in Unity); Unity Entities (DOTS) is Unity's own. EasyEcs is an allocation-free archetype ECS for .NET 10 game servers and simulations: systems are `[ForEach]` methods that a source generator compiles into struct jobs, and a server tick of 100,000 entities takes 1.72 ms and allocates 0 B. BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## The three parts ```mermaid flowchart LR subgraph Entities E1["Entity 1"] E2["Entity 2"] E3["Entity 3"] end subgraph Components P["Position"] V["Velocity"] H["Health"] end subgraph Systems M["MovementSystem
Position + Velocity"] D["DeathSystem
Health"] end E1 --- P & V & H E2 --- P & H E3 --- P & V M -->|reads Velocity, writes Position| P D -->|reads| H ``` **Entity** An **entity** is an identity and nothing else: no fields, no methods. In EasyEcs it is a small handle (world, id, version). Ids are recycled, and the version tells a live entity from a destroyed one that used the same id, so a stale handle never reaches the wrong entity. ```csharp Entity unit = world.CreateEntity(new Position(0, 0), new Health(100)); ``` **Component** A **component** is plain data: a struct with fields and no behaviour. An empty struct is a **tag**, a yes-or-no state such as `Dead` or `Stunned`. Data that exists once per world (the clock, the map) is a **singleton**. ```csharp public record struct Position(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent; public struct Dead : IComponent; // a tag public record struct Clock(float Dt) : ISingletonComponent; // one per world ``` **System** A **system** is the logic. It names the components it reads and writes, and the ECS runs it over every entity that has them. Systems do not call each other: they cooperate through the data they write. ```csharp public class MovementSystem : EcsSystem { [ForEach, Without] static void Move(ref Position p, in Velocity v, in Clock clock) { p.X += v.X * clock.Dt; p.Y += v.Y * clock.Dt; } } ``` A **query** is the question a system asks: "every entity with `Position` and `Velocity` but without `Dead`". The answer changes as entities gain and lose components, which is how an entity changes behaviour: add `Velocity` and it starts moving, add `Dead` and every system that excludes `Dead` stops seeing it. ## How an ECS stores components The way components are laid out in memory decides what is fast. There are two common designs. ### Archetypes An **archetype** is one combination of component types. Every entity with exactly `Position + Velocity + Health` lives in the same table, one row per entity and one column per component (a structure of arrays). A query finds the tables whose combination includes what it asks for and walks their columns front to back. ```mermaid flowchart TB subgraph A["Archetype: Position + Velocity + Health"] direction LR A1["Position[ ]: p0 p1 p2 p3"] A2["Velocity[ ]: v0 v1 v2 v3"] A3["Health[ ]: h0 h1 h2 h3"] end subgraph B["Archetype: Position + Health"] direction LR B1["Position[ ]: p4 p5"] B2["Health[ ]: h4 h5"] end ``` - **Iteration is linear.** The columns a system touches are contiguous arrays, which is what CPU prefetchers and SIMD handle best. There is no per-entity lookup. - **Changing an entity's set of components moves it** to another table: its row is copied column by column. Designs differ in how much this costs and when it happens: many libraries defer it to a command buffer applied later. Unity Entities, Bevy (by default), Flecs, Arch, Friflo.Engine.ECS and EasyEcs are archetype ECSs. ### Sparse sets A **sparse set** stores each component type on its own: a dense array of values, plus an index from entity id to position in that array. Adding or removing a component touches only that component's set; nothing else moves. - **Adding and removing are cheap**, and every component type is independent. - **Queries over several components** walk one set and look the entity up in the others, which is random access rather than a linear walk. EnTT and DefaultEcs store components this way; Bevy offers it per component type as an option. ### The trade-off | | Archetypes | Sparse sets | | ------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------- | | Iterating several components together | Linear walk over contiguous columns | One set walked, the others looked up per entity | | Adding or removing a component | The entity's row moves to another table | Only that component's set changes | | Memory per entity | One row per table, no per-type index | An index entry per component type | | Best when | Many entities share combinations and are updated every tick | Components come and go constantly, queries are narrow | EasyEcs is an archetype ECS that removes the usual cost of the archetype design for states that come and go: removing a component keeps the row and clears a presence bit, so toggling a status such as `Stunned` never moves data after the first time. The details are in [Architecture](https://ecs.xgamedev.net/en/docs/architecture#storage-model). ## How does an entity change what it does? By gaining and losing components. Adding, removing, creating and destroying are **structural changes**: they change which tables an entity lives in, or which entities exist. The hard case is a change made while a system is iterating over the very tables it changes, such as a death system that marks units `Dead` as it walks them. Most ECS libraries forbid that and give you a **command buffer**: the system records "add `Dead` to entity 42", and the buffer plays the changes back after the loop. It works, but systems then see a state that is about to change, and the order of effects depends on when buffers are played back. EasyEcs applies every structural change at once, even in the middle of a pass. A pass still visits each entity at most once, entities that join a table during the pass wait for the next one, and the systems that run later in the same update see the change. See [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes). ## Can an ECS run systems in parallel? Yes, and this is one of its strengths. A system declares what it reads and what it writes; two systems that write nothing the other touches can run at the same time without locks. In EasyEcs the declaration is the method itself: `ref Position` is a write, `in Velocity` a read, and the generator turns those into the access the scheduler uses (`WorldOptions.ParallelSystems`). One heavy system can also split its rows across cores with `[ForEach(Parallel = true)]`. For a server, the simplest parallelism is often one world per thread, such as one per map or zone: worlds share nothing, so they need no synchronization at all. See [Threading](https://ecs.xgamedev.net/en/docs/guide/threading). ## Is an ECS faster than object-oriented code? For the work an ECS is built for, usually yes, for two reasons: memory layout and the absence of virtual dispatch. In typical object-oriented code, each game object is a class instance on the heap with its fields together, and its behaviour is a virtual `Update()` method. Updating 100,000 of them means following 100,000 references to scattered objects and making 100,000 virtual calls, each of which drags the whole object through the cache to read two fields. In an ECS, the movement system reads exactly two arrays, `Position` and `Velocity`, in order, and the loop body can be inlined. In EasyEcs, a `[ForEach]` system that adds `Velocity` to `Position` costs 0.91 ns per entity, against 1.28 ns for the same update written by hand over two plain arrays. BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The difference in how you design is just as large: | | Object-oriented | ECS | | ---------------------------- | --------------------------------------------- | -------------------------------------------------------------- | | A kind of thing | A class, often in an inheritance hierarchy | A combination of components | | Behaviour | Methods on the object | Systems over every matching entity | | Changing what something does | Change its class, or add flags and branches | Add or remove a component | | Shared state | Objects reference each other | Systems read and write components; singletons hold world state | | Memory | An object per thing, wherever the heap put it | A column per component, contiguous | Neither is better everywhere. Object-oriented code is a fine fit for a few long-lived objects with rich, distinct behaviour, such as services, UI and business workflows, and an ECS gains little there. ## When should you use an ECS? > **An ECS fits when** > > - Many entities (thousands to millions) share behaviour in different combinations. > - The world is updated in ticks, and most of the time goes into loops over those entities. > - Things change what they are at run time: a unit is stunned, burning, dead, then respawned. > - You want each piece of logic isolated, so it can be tested, reordered or run in parallel on its own. > **It is the wrong tool when** > > - There are a few dozen objects with very different behaviour. > - The work is request and response over a database, with no per-tick simulation. > - The data is deeply nested documents rather than flat, uniform records. Typical ECS workloads are game servers (zones, matches, MMO maps), real-time strategy and simulation games, physics and crowd simulations, robotics and traffic models, and digital twins. ## Is an ECS only for games? No. Games made the pattern popular because their worlds are large, uniform and updated every frame, but nothing in it is specific to games. Any program that simulates many similar things over time, such as a traffic model, an epidemic simulation, a market simulation or a fleet of IoT devices, has the same shape and benefits the same way. ## Isn't this just composition over inheritance? It starts there. "Composition over inheritance" builds an object from parts instead of a class hierarchy, and an ECS does the same with components. The difference is where the behaviour lives: composed objects still carry their methods and call each other, while an ECS moves all behaviour into systems that run over every entity with the right parts. That is what makes the data contiguous and each system independent. ## Which ECS libraries are there for C# and .NET? | Library | Storage | Runs on | | --------------------- | ------------------------------------ | ------------------------------- | | EasyEcs | Archetypes, presence bits per column | .NET 10 (servers, tools, tests) | | Friflo.Engine.ECS | Archetypes | .NET and Unity | | Arch | Archetypes in chunks | .NET and Unity | | DefaultEcs | A pool per component type | .NET and Unity | | Unity Entities (DOTS) | Archetypes in chunks | Unity only | Measured against Friflo.Engine.ECS, Arch and DefaultEcs in 37 head-to-head benchmarks, each library doing the same work its own idiomatic way, EasyEcs is faster in 24 and within the measurement error in 11. On a whole server tick of 100,000 entities, Friflo.Engine.ECS takes 1.08× the time of EasyEcs, Arch 3.4× and DefaultEcs 3.7×, and only EasyEcs and Friflo allocate nothing per tick. Every result, sorted by lead: [Comparison](https://ecs.xgamedev.net/en/docs/comparison#feature-by-feature). ## What does EasyEcs add? EasyEcs is an archetype ECS for C# and .NET 10 servers. On top of the pattern above it gives you: - **Systems written as methods.** A `[ForEach]` method is the whole system; a source generator turns it into an inlined struct job, and filters are attributes. - **Immediate structural changes.** Add, remove, create and destroy in the middle of a pass, with no command buffer. - **No garbage per tick.** After warm-up, updates, queries and structural changes allocate nothing; a full server tick of 100,000 entities takes 1.72 ms. - **Design rules checked at compile time.** The analyzer rejects stateful systems, systems that call each other and writes through `in`. - **The rest of a server's needs built in:** change and removal tracking, value indexes, relations and a hierarchy, prefabs, dynamic buffers, snapshots, saves and moving entities between worlds ([Features](https://ecs.xgamedev.net/en/docs/features)). The words used on this page and the rest of the docs are defined in the [Glossary](https://ecs.xgamedev.net/en/docs/glossary). - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): Build a small simulation step by step. - [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles): How to design features as data plus one-job systems. - [Features](https://ecs.xgamedev.net/en/docs/features): Every feature, what it is for and what it costs. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): EasyEcs next to Friflo.Engine.ECS, Arch and DefaultEcs. --- # Features > Every EasyEcs feature on one page, grouped by job. What each does, when to use it, what it costs, how it compares with Arch, Friflo and DefaultEcs. URL: https://ecs.xgamedev.net/en/docs/features Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/features.md Every feature of EasyEcs on one page, grouped by the job it does on a server: simulate a world, react to what changed, find entities, structure them, persist them, and scale across cores. Each entry says what the feature does, when to use it and when not, what it costs, and links to its guide page. Every feature below ships in the one `EasyEcs` package, works on the same world, allocates nothing on its hot path after warm-up, and is covered by the unit tests and a BenchmarkDotNet benchmark. The [battle server](https://ecs.xgamedev.net/en/docs/example) uses all of them in one program; its full tick of 100,000 units takes 2.97 ms. BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## At a glance | Job | Features | | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Simulate](https://ecs.xgamedev.net/en/docs/features#simulate) | [worlds and entities](https://ecs.xgamedev.net/en/docs/features#worlds-and-entities), [components and tags](https://ecs.xgamedev.net/en/docs/features#components-and-tags), [generated members](https://ecs.xgamedev.net/en/docs/features#generated-members), [systems and `[ForEach]`](https://ecs.xgamedev.net/en/docs/features#systems-and-foreach), [generic systems](https://ecs.xgamedev.net/en/docs/features#generic-systems), [filters](https://ecs.xgamedev.net/en/docs/features#filters), [optional components](https://ecs.xgamedev.net/en/docs/features#optional-components), [batch methods](https://ecs.xgamedev.net/en/docs/features#batch-methods), [singletons](https://ecs.xgamedev.net/en/docs/features#singletons), [ordering, groups and intervals](https://ecs.xgamedev.net/en/docs/features#system-groups-and-intervals), [immediate structural changes](https://ecs.xgamedev.net/en/docs/features#immediate-structural-changes), [ad-hoc queries](https://ecs.xgamedev.net/en/docs/features#ad-hoc-queries) | | [React to changes](https://ecs.xgamedev.net/en/docs/features#react) | [change tracking](https://ecs.xgamedev.net/en/docs/features#change-tracking), [removal detection](https://ecs.xgamedev.net/en/docs/features#removal-detection), [cleanup components](https://ecs.xgamedev.net/en/docs/features#cleanup-components), [disable and enable](https://ecs.xgamedev.net/en/docs/features#disable-and-enable) | | [Find](https://ecs.xgamedev.net/en/docs/features#find) | [value indexes](https://ecs.xgamedev.net/en/docs/features#value-indexes), [ordered ranges](https://ecs.xgamedev.net/en/docs/features#ordered-ranges), [table groups](https://ecs.xgamedev.net/en/docs/features#table-groups) | | [Structure](https://ecs.xgamedev.net/en/docs/features#structure) | [relations](https://ecs.xgamedev.net/en/docs/features#relations), [hierarchy](https://ecs.xgamedev.net/en/docs/features#hierarchy), [dynamic buffers](https://ecs.xgamedev.net/en/docs/features#dynamic-buffers), [prefabs and cloning](https://ecs.xgamedev.net/en/docs/features#prefabs-and-cloning) | | [Persist](https://ecs.xgamedev.net/en/docs/features#persist) | [snapshots](https://ecs.xgamedev.net/en/docs/features#snapshots), [saves](https://ecs.xgamedev.net/en/docs/features#saves), [migration](https://ecs.xgamedev.net/en/docs/features#migration), [unloading plugin types](https://ecs.xgamedev.net/en/docs/features#unloading) | | [Scale](https://ecs.xgamedev.net/en/docs/features#scale) | [one world per thread](https://ecs.xgamedev.net/en/docs/features#threading-model), [parallel systems](https://ecs.xgamedev.net/en/docs/features#parallel-systems), [parallel `[ForEach]`](https://ecs.xgamedev.net/en/docs/features#parallel-foreach), [bulk operations](https://ecs.xgamedev.net/en/docs/features#bulk-operations) | | [Build and operate](https://ecs.xgamedev.net/en/docs/features#operate) | [analyzer and code fixes](https://ecs.xgamedev.net/en/docs/features#analyzer), [per-system timing](https://ecs.xgamedev.net/en/docs/features#per-system-timing), [errors](https://ecs.xgamedev.net/en/docs/features#errors), [introspection](https://ecs.xgamedev.net/en/docs/features#introspection), [Native AOT](https://ecs.xgamedev.net/en/docs/features#native-aot), [hosting and testing](https://ecs.xgamedev.net/en/docs/features#hosting-and-testing), [templates and samples](https://ecs.xgamedev.net/en/docs/features#templates) | ## Simulate The core of every tick: data in tables, logic in systems, and the loop that runs them. ```csharp public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent, ITrackChanges; public record struct Armor(int Value) : IComponent; public struct Dead : IComponent; public record struct Clock(float Dt) : ISingletonComponent; public class MovementSystem : EcsSystem { [ForEach, Without] static void Move(ref Position p, in Velocity v, in Clock clock) => p = new Position(p.X + v.X * clock.Dt, p.Y + v.Y * clock.Dt); } ``` ### Worlds and entities A `World` owns entities, components, singletons and systems; worlds share nothing. An `Entity` is a 16-byte handle (world, index, version): ids are recycled, and every access checks the version, so a handle to a destroyed entity throws instead of reaching the entity that reuses its id. - **Use it for:** one world per independent simulation (a map, a zone, a match, a test). Keep `Entity` handles in code and `EntityId`s in components. - **Cost:** a 16-byte record per entity id. Creating with its components is one placement in the final table; destroying fills the hole with the table's last row. `WorldOptions.InitialEntityCapacity`, `EnsureEntityCapacity(n)` and `EnsureCapacity(n)` (the table too) pre-size for a known peak, so a long-running server never grows at run time. - **Guide:** [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components) ### Components and tags A component is a struct (`IComponent`) in archetype tables: one table per component set, one column per component, one row per entity. Unmanaged columns are pinned and start on a 64-byte boundary. An empty struct is a tag. Removing a component clears a presence bit and keeps the row, so adding it back is just as cheap. - **Use it for:** per-entity data split by what systems read together; tags for states that come and go. - **Skip it for:** values that change every tick on most entities as a tag: use a field. - **Cost:** a pass loads only the columns it reads. Gaining a component the table has no column for copies the row once; after that, toggling it flips a bit. - **Guide:** [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components) ### Generated members The source generator gives each component named C# 14 extension members: `e.Position`, `HasPosition`, `SetPosition(x, y)`, `RemovePosition()`, `IsDead` for a tag, `world.Clock` for a singleton, `world.TeamIndex` for an indexed component, and the same writers on a `Prefab`. Tracked and indexed components get a read-only property, so a read is never a write. - **Use it for:** all code that names a concrete component. The generic API (`Get()`, `Set(…)`) stays for generic code. - **Cost:** none. Each member is an inlined call to the generic API, and the generator knows which ones are structural. - **Guide:** [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components), [Cheat sheet](https://ecs.xgamedev.net/en/docs/cheat-sheet#generated-members) ### Systems and [ForEach] A system derives from `EcsSystem` and has one job. A `[ForEach]` method is its whole loop: components (`ref` to write, `in` to read), singletons, the `Entity`, the `World`. The generator compiles each method into a struct job that the JIT inlines into the row loop. `OnCreate`, `OnUpdate` and `OnDestroy` cover setup and per-update work. - **Use it for:** all per-entity logic of a tick. - **Cost:** a `[ForEach]` system that adds `Velocity` to `Position` costs 0.91 ns per entity, against 1.28 ns for the same loop over two plain arrays. Per system and update: three virtual calls plus one query-cache lookup per method. - **Guide:** [Systems](https://ecs.xgamedev.net/en/docs/guide/systems), [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles) ### Generic systems A system class can be generic: each closed type (`CountOf`, `CountOf`) is a system of its own, with its own generated job and access set, added, ordered and scheduled on its own. A closed generic system can also be a base class. - **Use it for:** one rule applied to several component types (a counter, a decay, a cleanup per kind of resource). - **Skip it for:** a generic `[ForEach]` method: nothing would supply its type arguments ([EECS004](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs004)); make the class generic instead. - **Cost:** none beyond the closed systems; a type built by reflection has its code closed on first use. - **Guide:** [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#generic-systems) ### Filters `[With]` requires a component that is not passed in, `[Without]` excludes one, `[WithAny]` requires one of several, `[Changed]` and `[Removed]` select by change tick. The same filters exist as a `QueryFilter` for ad-hoc code. A system group carries `[With]`, `[Without]` and `[WithAny]` for all its systems, or implements `IGroupWith` / `IGroupWithout`, itself or through an interface it implements: a generic interface then gives each actor type its own filtered group, where an attribute could not name the type parameter. - **Use it for:** states (`[Without]`), roles (`[With]`), alternatives (`[WithAny, WithAny]`). - **Cost:** matching is cached per query shape; a table that cannot match is skipped once, a table where some rows lack a component is tested 64 rows per bit word. - **Guide:** [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries), [Group filters](https://ecs.xgamedev.net/en/docs/guide/systems#group-filters) ### Optional components A `Maybe` parameter visits every entity whether or not it has `T`: `HasValue` says which, `Value` is the `ref`. One method replaces a `[With]` and a `[Without]` variant when the optional part is small. - **Use it for:** a bonus that only some entities have (armor on a damage roll, a buff on regeneration). - **Skip it for:** the hottest loops: two methods with `[With]` / `[Without]` test nothing per row. - **Cost:** one presence-bit test per row in a method that makes no structural change; a lookup per entity in one that does. - **Guide:** [Systems](https://ecs.xgamedev.net/en/docs/guide/systems) ### Batch methods A `[ForEach]` method that takes `Span` / `ReadOnlySpan` receives whole runs of matching rows, one call per run, for code you vectorize with `Vector`. `world.ForEachBatch` does the same for ad-hoc jobs. - **Use it for:** arithmetic over many rows (movement, decay, sums). - **Skip it for:** logic that changes structure: the world's structure is frozen during a batch method. - **Cost:** one call per run of rows instead of one per entity. - **Guide:** [Systems](https://ecs.xgamedev.net/en/docs/guide/systems) ### Singletons One struct per world (`ISingletonComponent`): clock, configuration, counters, a spatial grid. A `[ForEach]` method takes it as a `ref` or `in` parameter; `SingletonRef` is a stable handle for code outside systems. - **Use it for:** all world-level state. Systems keep none. - **Instead of:** a static field, which every world would share. - **Cost:** one lookup per pass for a parameter. - **Guide:** [Singletons](https://ecs.xgamedev.net/en/docs/guide/singletons) ### Ordering, groups and intervals Systems run in registration order, moved by `[UpdateBefore]` / `[UpdateAfter]`. `[UpdateInGroup]` puts a system in a group that runs on `world.Update()` only. `UpdateInterval` and `UpdatePhase` run a system every N-th update, spread over phases; `Enabled` switches it off. A group's filters (`[Without]`, or `IGroupWith` / `IGroupWithout` on the group or an interface it implements) apply to every `[ForEach]` method of its systems. - **Use it for:** different cadences: input on every wake-up, simulation on a fixed tick, saving every few seconds; one group per kind of actor, declared once through a generic interface. - **Cost:** none beyond the systems; an empty group is a no-op. Cycles fail the build ([EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019)). - **Guide:** [Systems](https://ecs.xgamedev.net/en/docs/guide/systems) ### Immediate structural changes Create, destroy, add and remove apply at once, also inside a pass over the same tables. A pass visits each entity at most once: entities that leave before their turn are skipped, entities that join wait for the next pass, and the `ref` parameters of a `[ForEach]` method stay valid when the body moves its own entity. - **Use it for:** always. Write the change where the decision is made; later code and later systems of the same update see it. - **Compared with command buffers:** libraries that defer changes to a buffer show systems a state that is about to change, and the order of effects depends on when the buffer is played back. EasyEcs has no buffer to flush. - **Cost:** a pass that may change structure checks one counter after each entity; methods that cannot change structure skip even that. - **Guide:** [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes), [ref and await](https://ecs.xgamedev.net/en/docs/guide/refs-and-await) ### Ad-hoc queries Iteration from any code: `foreach (var item in world.Query(filter))`, struct jobs (`world.ForEach`, `ForEachEntity`), `world.Count` and `world.Any`. A static `[ForEach]` method outside a system gets a generated entry point (`Reports.CountAlive(world, ref alive)`) that runs it as a struct job with the caller's values. `entity.Run(ref job, filter)` runs a struct job on one entity, with the refs a pass would give it: `false` when the entity is not alive, lacks a component or fails the filter. A job's `static int Writes` names the components that count as written (default: all); a job implementing `INoStructuralChanges` skips the structural bookkeeping. - **Use it for:** tools, tests, request handlers between updates, one-off passes; `entity.Run` for a request or a message to one entity. - **Skip it for:** per-tick logic: a system is ordered, scheduled and measured. - **Cost:** allocation-free. `Count` sums table counts; `Any` stops at the first match; a struct job is the fastest ad-hoc pass. `entity.Run` is O(1), plus O(1) per component its filter names. - **Guide:** [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries), [One entity: `entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity) ## React to changes Servers spend much of their time on what changed since the last tick: replication, saving, re-indexing. EasyEcs records changes as data, so a system visits only those rows. ```csharp public record struct Replica(int Health) : IComponent; public class ReplicationSystem : EcsSystem { [ForEach, Changed] // only rows written since this system last ran static void Send(in Health hp, ref Replica replica) => replica = new Replica(hp.Value); } ``` ### Change tracking A component marked `ITrackChanges` records the change tick of each row's last write (any access that hands out a `ref`). A `[Changed]` method visits only the rows written since its system last ran; `QueryFilter.Changed(since)` does the same for queries. - **Use it for:** replication to clients, saving dirty entities, updating a spatial structure for the units that moved. - **Skip it for:** components written on every row every tick (there is nothing to skip). - **Cost:** 8 bytes per row and one store per write; untracked components pay nothing. Replicating 10 changed entities of 100,000 takes 525 ns, against 38.6 μs for a scan of every row. - **Guide:** [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking) ### Removal detection A `[Removed]` method visits the entities that lost a tracked `T` since its system last ran, once per removal, with their other components: removing keeps the row and stamps its tick. - **Use it for:** telling clients what went away (a fire went out, a shield broke), releasing what a component stood for (a reserved cell). - **Skip it for:** destroyed entities, which have no row: mark them with a tag that replication reads, and destroy them after it ran. - **Cost:** no storage beyond the tick column the component already has. Finding 10 removals among 100,000 entities takes 830 ns. - **Guide:** [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking#removal-detection) ### Cleanup components A component implementing `ICleanupComponent` outlives the destruction of its entity: destroying it removes the other components and adds the `Destroyed` tag, and the entity stays until a system releases the resource and removes the last cleanup component. - **Use it for:** resources outside the world that must be released exactly once: a socket, a reserved seat, a slot in another service. - **Skip it for:** plain data: a destroyed entity's components need no release. - **Cost:** tables without a cleanup component pay one flag check per destroy. - **Guide:** [Cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) ### Disable and enable `entity.Disable()` hides a component from queries, `Has` and `Get` and keeps its value; `Enable()` gives it back. The entity carries the tag `Disabled` meanwhile, so the paused entities are one query away. - **Use it for:** pausing: a cooldown frozen while stunned, an AI switched off while a player controls the unit. - **Skip it for:** values you will not need again: remove the component. - **Cost:** O(1); the first disable in a table moves the row once to the table with the tag's column. - **Guide:** [Cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) ## Find Lookups by value without a dictionary kept in sync by hand. ```csharp public record struct Team(int Id) : IComponent, IIndexed { public int Key => Id; } public record struct Zone(int Id) : IComponent, IGroup { public int Group => Id; } ``` ```csharp using var world = new World(); world.GroupBy(); // at setup world.CreateEntity(new Team(1), new Zone(3), new Position(0, 0)); int red = world.TeamIndex.Count(1); // a hash probe int inZone = world.Count(QueryFilter.Create().InZone(3)); // walks zone 3's rows only ``` ### Value indexes A component implementing `IIndexed` is found by its `Key`: `world.Index()` (or `world.TeamIndex`) with `Find`, `TryFind` and `Count`. Every `Set`, create and destroy keeps the index current; writes through a `ref`, which the index could not see, fail the build ([EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015)). - **Use it for:** a player by name, the units of a guild, the entities in a grid cell. - **Skip it for:** values that change on most rows every tick and are looked up rarely: every change is a re-link. - **Cost:** one node per indexed entity, paid only by worlds that use the index. `Count` is a hash probe, `Find` one step per match. - **Guide:** [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) ### Ordered ranges A value index whose key is comparable also walks in key order: `Range(min, max)`, `RangeDescending`, `Ascending()` and `Descending()`. - **Use it for:** leaderboards, matchmaking by rating, the players of a level range. - **Cost:** the sorted key list is kept as keys appear and disappear: O(log keys) plus a block move each. - **Guide:** [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) ### Table groups After `world.GroupBy()`, the value of an `IGroup` component splits tables: the entities of one zone, map or match share tables, and `QueryFilter.InGroup(group)` walks only their rows, contiguous in memory. Setting a new value moves the entity to its group's tables. - **Use it for:** many zones or matches in one world, each updated or queried on its own. - **Skip it for:** values that change often (each change is a row copy) or a handful of entities per group. - **Cost:** O(entities) once at `GroupBy`; one row copy per change of group. - **Guide:** [Groups](https://ecs.xgamedev.net/en/docs/guide/groups) ## Structure Links between entities, lists inside entities, and kinds of entities to spawn from. ```csharp public record struct OwnedBy(EntityId Owner) : IComponent, IIndexed { public EntityId Key => Owner; } public record struct Loot(int Item); ``` ```csharp var archer = world.CreateEntity(new Health(10)); world.CreateEntity(new OwnedBy(archer), new Position(0, 0)); // an arrow points at its owner int arrows = world.OwnedByIndex.Count(archer); var turret = world.CreateEntity(new ChildOf(archer)); // destroyed with its parent archer.Set(new DynamicBuffer()); archer.WriteLoot().Add(new Loot(7)); // a tracked write var goblin = new Prefab().SetPosition(0, 0).SetHealth(30); var wave = new Entity[100]; world.Instantiate(goblin, wave); ``` ### Relations A component indexed by an `EntityId` links each entity to one target (an arrow to its archer), and the index lists the entities pointing at a target. An `IRelation` element links an entity to many targets (a hero in several parties) through `AddRelation` / `RemoveRelation`, with `world.Relations()` for the reverse lookup. `WhenTargetDestroyed(TargetPolicy…)` decides what a link does when its target dies: keep, remove or destroy. - **Use it for:** ownership, party membership, the units a buff applies to, items with state of their own. - **Skip it for:** a bag of plain values only its owner reads: a [dynamic buffer](https://ecs.xgamedev.net/en/docs/features#dynamic-buffers) is one component instead of an entity per item. - **Cost:** reverse lookups are O(1) to start and O(1) per link; an `IRelation` link costs 20 bytes plus 8 in its target's list, recycled. - **Guide:** [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) ### Hierarchy The built-in `ChildOf(EntityId Parent)` component links a child to its parent. `world.Children(parent)` lists the children, `world.Descendants(root)` walks the whole subtree depth first (each entity before its children, the root excluded), `Set(new ChildOf(other))` re-parents, and destroying a parent destroys its descendants. - **Use it for:** a ship and its turrets, a player and the items attached to them, a squad and its members. - **Skip it for:** transform propagation: there is no built-in world transform; write the system that needs it. - **Cost:** `Children` is O(1) to start and O(1) per child, after the first call indexes every `ChildOf`; `Descendants` is O(1) per entity and allocates nothing once warm; a cascade is O(1) per link. - **Guide:** [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy) ### Dynamic buffers `DynamicBuffer` is a list per entity, held as a tracked component. Its writes (`Add`, `RemoveAt`, `Clear`, `AsSpan`) take the buffer by `ref`, so `[Changed>]` visits the entities whose list changed and a write through `in` does not compile. Snapshots copy the elements. - **Use it for:** lists that belong to one entity and are sent or saved when they change: a bag, a path, recent hits. - **Skip it for:** items with their own state (one entity per item with a relation) or a small fixed set (an `[InlineArray]` in an unmanaged component). - **Cost:** one object and one array per entity, made by the first write; writes within the capacity allocate nothing. - **Guide:** [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers), [ECS principles, rule 8](https://ecs.xgamedev.net/en/docs/ecs-principles#8-choose-how-to-hold-a-collection) ### Prefabs and cloning A `Prefab` is a recipe of component values that belongs to no world, so no query sees it and no system filters it out. `world.Instantiate(prefab)` creates an entity, `Instantiate(prefab, span)` a wave; `new Prefab(base)` makes a variant, `AddMember()` a group (a boss with its minions). `entity.Clone()` copies a living entity. - **Use it for:** kinds of entities spawned again and again: NPC types, projectiles, loot, defined in code or loaded from configuration. - **Skip it for:** entities whose values all differ: create them with their values. - **Cost:** one row copy per instance; a wave passes the structural gate once and grows its table at most once. - **Guide:** [Prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs) ## Persist A world is data, so it can be copied, written out, moved and reloaded. ```csharp var before = world.Capture(); // in memory world.Update(); world.Restore(before); // rolled back; handles from before are valid again var bytes = new System.Buffers.ArrayBufferWriter(); world.Save(bytes); // to bytes: a file, a database, another process using var restarted = new World(); restarted.Load(bytes.WrittenSpan); ``` ### Snapshots `world.Capture()` copies entities, components and singletons into a `WorldSnapshot`; `world.Restore(snapshot)` puts them back, any number of times. `Capture(into)` reuses a snapshot's arrays. - **Use it for:** undoing a turn, rollback for client prediction, replays, resetting a world between tests. - **Skip it for:** persistence across restarts (use [saves](https://ecs.xgamedev.net/en/docs/features#saves)); managed references inside components are shared, not cloned. - **Cost:** O(entities × components) both ways; capturing into a reused snapshot allocates nothing. - **Guide:** [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots) ### Saves `world.Save(writer)` writes a whole world as bytes and `world.Load(bytes)` reads it into a world of this or another process: same ids, components and singletons. Unmanaged components are their raw rows; managed components, singletons and the unmanaged components marked `[NinoType]` are written by Nino. Types are recorded by Nino type id, so a load skips components the process no longer has, and `[NinoFormerName]` keeps a renamed one. - **Use it for:** persistence across restarts, replays on disk, shipping a world to another machine. - **Skip it for:** changing an unmanaged component's layout in place: add a new component type, or old saves will not load. - **Cost:** one block copy per unmanaged column; allocates nothing once its buffers are large enough. - **Guide:** [Saves](https://ecs.xgamedev.net/en/docs/guide/saves) ### Migration `SaveEntities` and `LoadEntities` move a group of entities (a player and what they own) to another world through bytes, with new ids and the links inside the group rewritten. `MoveEntities` does it between two worlds of the same thread without encoding. A record saves only what persists: `SaveEntities(writer, ids, set)` with a `ComponentSet` writes the components of the set, and `LoadEntitiesInto(bytes, entities)` puts them onto entities that exist already; with `markWritten: false` the restored values do not count as changed, so a saver of changed rows does not write them straight back. - **Use it for:** a player changing zone or server, a match handing its survivors to a lobby (collect the group with `Descendants`); records for actors whose entity exists before its stored state arrives. - **Cost:** O(entities given × components); `MoveEntities` copies rows directly. - **Guide:** [Migration and unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload), [Records](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records) ### Unloading plugin types `world.RemoveTypes(assembly)` or `RemoveTypes(context)` removes a plugin's systems, singletons, indexes and components from a world, so a collectible `AssemblyLoadContext` can unload and a new version can load, with the data carried over by a save. - **Use it for:** hot-reloading game logic on a live server. - **Cost:** O(entities with such components + tables + cached queries), on a cold path that allocates. - **Guide:** [Migration and unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload) ## Scale More entities, more cores, bigger waves. ### One world per thread A world has one owner thread, the one calling `Update`. Structural changes check a plain owner flag (no atomics) and throw instead of corrupting the tables when made from a parallel region; the analyzer reports the off-thread changes it can see ([EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013), [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014)). - **Use it for:** one world per map or zone, each on its own thread, with no synchronization. Input from other threads goes through a queue you own, drained by a system. - **Cost:** four worlds of 25,000 entities on four threads tick in 924 μs, against 1.72 ms for one world of 100,000. - **Guide:** [Threading](https://ecs.xgamedev.net/en/docs/guide/threading) ### Parallel systems With `WorldOptions.ParallelSystems`, consecutive systems with no order and no conflicting access run at the same time. The access is generated from the `ref` and `in` parameters, and the result always equals the sequential order. - **Use it for:** several heavy, independent systems and spare cores. - **Skip it for:** light systems over a few thousand entities: a stage costs a thread-pool hand-off. - **Cost:** allocation-free; `MaxDegreeOfParallelism` bounds the threads. - **Guide:** [Threading](https://ecs.xgamedev.net/en/docs/guide/threading) ### Parallel [ForEach] `[ForEach(Parallel = true)]` cuts one method's rows into chunks that the calling thread and thread-pool threads run at once. The analyzer rejects methods that could race ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010)): structural changes, batch methods, singletons taken by `ref`. `world.ForEachParallel` and `ForEachEntityParallel` do the same for struct jobs. - **Use it for:** heavy per-entity work over tens of thousands of entities: steering, path following, AI scoring. - **Cost:** chunks of 1,024 to 16,384 rows, about four per thread, allocation-free. - **Guide:** [Threading](https://ecs.xgamedev.net/en/docs/guide/threading) ### Bulk operations `world.CreateEntities(span, a, b)` spawns a wave with the same values, `Instantiate(prefab, span)` a wave of a prefab, `DestroyEntities(filter)` destroys every match. `SetAll`, `RemoveAll`, `DisableAll` and `EnableAll` change one component on every match, whole 64-row words at a time. - **Use it for:** waves of monsters, clearing a zone, a round reset, a status lifted from everyone. - **Cost:** one pass through the structural gate per call and at most one table growth. - **Guide:** [Bulk operations](https://ecs.xgamedev.net/en/docs/guide/bulk) ## Build and operate What keeps a code base correct as it grows, and a server observable while it runs. ### Analyzer and code fixes The package bundles an analyzer (EECS002 to EECS034) and code fixes next to the generator. Invalid `[ForEach]` methods, class components, stateful systems, systems that reference systems, writes through `in`, unsafe parallel methods, off-thread structural changes, indexed components written through a `ref` and ordering cycles fail the build; a few warnings flag code that works but costs. - **Use it for:** always; it is on by default and keeps systems decoupled. - **Guide:** [Analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer) ### Per-system timing With `WorldOptions.MeasureSystems`, every run of a system is timed: `system.Stats` holds `Runs`, `Last`, `Total` and `Average`. - **Use it for:** a diagnostics endpoint or a log line on a live server, to see which system grows. - **Cost:** two timestamp reads per system run when on; nothing when off. - **Guide:** [Debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics#timing), [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#measuring-systems) ### Errors By default an exception a system throws propagates out of `Update()`. With `WorldOptions.SystemErrors = SystemErrorPolicy.Disable`, the failing system is switched off, its exception stays in `system.Error`, and the update goes on; setting `Enabled = true` retries it. - **Use it for:** `Disable` on a live server, where a failure becomes data a health check reads; `Throw` in tests. - **Cost:** nothing until a system throws. - **Guide:** [Debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics#errors), [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#errors) ### Introspection `world.Describe()` lists tables with their columns, rows, capacity and bytes; `entity.Describe()` lists an entity's component values. A debugger shows an entity's components directly. - **Use it for:** admin tools, memory reports, debugging. - **Cost:** allocates the description (a cold path), never touches the hot paths. - **Guide:** [Debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics) ### Native AOT Systems, jobs and filters are generated at compile time; nothing on the hot paths uses reflection. The library is built with the trimming and AOT analyzers on, so `true` needs nothing else for EasyEcs. - **Use it for:** small, fast-starting server containers. ### Hosting and testing A world runs in an ASP.NET Core app or a Worker Service as one hosted service that owns it: it builds the world, runs its tick, takes requests through a channel and saves on shutdown. A system is tested with a world of its own: arrange entities and singletons, call `world.Update()`, assert on the data. - **Use it for:** every real server and every system. - **Cost:** none from EasyEcs: no hosting or test package, the pattern is a few classes of your own. - **Guide:** [Hosting](https://ecs.xgamedev.net/en/docs/guide/hosting), [Testing systems](https://ecs.xgamedev.net/en/docs/guide/testing) ### Templates and samples `dotnet new easyecs` creates a console server with a fixed tick: `Components/`, `Systems/` with one system per file (a prefab spawner among them) and a `Program.cs` that only hosts the world (`--tests` adds an NUnit project with a test file per system); `dotnet new easyecs-system` adds a system. [`samples/`](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples) has complete programs in learning order (hello world, a game loop, saving and loading, one world per thread, hot reload, actors), and the guide pages of features such as [change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking#full-example) end their "How to use it" part with a full example. - **Guide:** [Getting started](https://ecs.xgamedev.net/en/docs/getting-started), [Structuring a real project](https://ecs.xgamedev.net/en/docs/guide/project-structure) ## Compared with other libraries Each comparison does the same work in each library its own idiomatic way, with identical results checked in setup. EasyEcs is faster in 24 of 37 and within the measurement error in 11 more; its biggest leads over the fastest other library: | What is measured | EasyEcs | Next fastest | Its time vs EasyEcs | The others | | ------------------------------------------------------------------------------------------------------------------------------ | ------- | ------------------------------------- | ------------------- | ---------------------------------------------------------- | | [Save 10,000 entities and load them back](https://ecs.xgamedev.net/en/docs/comparison#saves) | 146 μs | DefaultEcs 4.33 ms, 4.37 MB allocated | 30× | Friflo.Engine.ECS 143×, 6.52 MB allocated | | [Add a component to 100,000 entities by query, then remove it](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 78.7 μs | Arch 1.21 ms | 15× | DefaultEcs 103×; Friflo.Engine.ECS 154×, 4.00 MB allocated | | [Spawn 10,000 entities beside 100,000, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 138 μs | Friflo.Engine.ECS 380 μs | 2.75× | Arch 2.96×; DefaultEcs 9.7×, 313 KB allocated | | [Query 100,000 players by value: a rating range, zone sums](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 127 μs | Friflo.Engine.ECS 317 μs | 2.49× | — | | [Create 1,000 parent-child squads, destroy them in cascade](https://ecs.xgamedev.net/en/docs/comparison#hierarchy) | 452 μs | Friflo.Engine.ECS 1.06 ms | 2.35× | — | | [Count 100 inventories through an index (1 item traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 425 ns | DefaultEcs 838 ns | 1.97× | Friflo.Engine.ECS 3.2× | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The same server tick, ported to each library (100,000 entities), is closer, since most of a tick is iteration bound by memory: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Every result, sorted by lead, with where another library is faster and why: [Comparison](https://ecs.xgamedev.net/en/docs/comparison#feature-by-feature). | | EasyEcs | Friflo.Engine.ECS | Arch | DefaultEcs | | -------------------------------- | ----------------------------------- | ------------------------------- | ----------------------------- | -------------------------- | | Storage | Archetypes, presence bits | Archetypes | Archetypes in chunks | A pool per component | | Structural changes inside a loop | Immediate, each entity visited once | Throw; a command buffer instead | Not guarded; a command buffer | Unsafe; a command recorder | | Source-generated systems | Yes | No | No (in core) | No | | Compile-time analyzer | Yes | No | No | No | | Change tracking by tick | Yes | No | No | `WhenChanged()` | | Removal detection | `[Removed]` | Events | Events | `WhenRemoved()` | | Value index | Yes | Yes | No | `EntityMap` | | Relations and hierarchy | Yes | Yes | No | No | | Parallel systems | Generated access | No | No | `ParallelSystem` | | Snapshots / saves | Both | JSON | No | Text, binary | | Unity | No (net10.0) | Yes | Yes | Yes | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The full comparison, with the cases each library is best at: [Comparison](https://ecs.xgamedev.net/en/docs/comparison). ## Related - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): Build a small simulation step by step. - [The battle server](https://ecs.xgamedev.net/en/docs/example): Every feature in one server, also a benchmark and a test. - [Performance](https://ecs.xgamedev.net/en/docs/performance): Which API to use when, with the numbers. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): EasyEcs next to Friflo.Engine.ECS, Arch and DefaultEcs. --- # Changelog > What changed in each EasyEcs release, newest first: new APIs, performance, fixes and the changes that need code changes. URL: https://ecs.xgamedev.net/en/docs/changelog Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/changelog.md What changed from one EasyEcs release to the next, newest first, for code that uses EasyEcs. Upgrading across a major or minor version that needs code changes? The [migration guide](https://ecs.xgamedev.net/en/docs/migration) has the steps. Each [GitHub release](https://github.com/JasonXuDeveloper/EasyEcs/releases) also lists every pull request it contains. ## 4.6.0 ### New - `world.Load(input, markWritten: false)` loads a whole save without change ticks: no loaded row counts as written or removed, also for systems added after the load, so a restart that resumes a saved world does not send every record again. See [restart](https://ecs.xgamedev.net/en/docs/guide/saves#restart). - `world.AddSystem(changesFromNow: true)` (and `AddSystem(system, changesFromNow: true)`) starts a system at the current tick: the first run of its `[Changed]` and `[Removed]` methods visits only what is written or removed after the call. See [ticks](https://ecs.xgamedev.net/en/docs/guide/change-tracking#ticks). ### Fixes - Native AOT publishes without warnings: a program with tracked components (`ITrackChanges`, also the built-in `ChildOf`) or disabled components got an IL3054 warning (generic recursion), which fails a build that treats warnings as errors. See [Native AOT](https://ecs.xgamedev.net/en/docs/faq#native-aot). ## 4.5.0 ### New - `entity.Run(ref job)` runs a struct job (`IForEachEntity`) on one entity: it returns false when the entity is stale or lacks a component, and `entity.Run(ref job, filter)` also when a `QueryFilter` (`With`, `Without`, `WithAny`, `Changed`, `Removed`, a group) rejects it. The job's `Writes` stamp change ticks as in a pass, its `ref` parameters stay valid across its own structural changes, and its writes reach the moved row even when it throws. See [one entity: `entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity). - A system group can filter through interfaces: `IGroupWith` / `IGroupWithout` on the group, or on an interface it implements, act as `[With]` / `[Without]`. A generic interface gives each type its own group (`IActorGroup : IGroupWith>`), which attributes cannot express. See [group filters](https://ecs.xgamedev.net/en/docs/guide/systems#group-filters). - `world.Descendants(root)` walks a whole subtree, depth first, allocation-free once warm: collect a group with every level of children before moving or saving it. See [list them](https://ecs.xgamedev.net/en/docs/guide/hierarchy#children). - `world.LoadEntitiesInto(input, entities, markWritten: false)` restores a record without counting it as a change, so `[Changed]` savers and replicators do not send it back; that holds for a value it replaces too, such as a prefab's default. See [a record of what persists](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records). - The EasyEcs package brings Nino's generator: a `[NinoType]` component gets its formatter with no other package reference, so a project can drop its `Nino.Generator` reference (a kept one must not be older than the Nino of EasyEcs). See [declare the components](https://ecs.xgamedev.net/en/docs/guide/saves#declare). - The analyzer treats `entity.Run` as a structural call: [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) rejects it in a parallel `[ForEach]` method, [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) and [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) check it like `Set`. ### Fixes - The analyzer treats `world.LoadEntitiesInto` as a structural call, like `LoadEntities`: it was missing from the members [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010), [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) and [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) check, so a call in a parallel `[ForEach]` method, in a method that promises no structural change or on another thread compiled without an error. ## 4.4.0 ### New - `world.SaveEntities(output, ids, set)` saves only the components of a `ComponentSet` (`ComponentSet.Create().With()`, or `With(typeof(Bank))` for types learned at run time): a record of what persists, without the runtime components around it, which then need no Nino formatter. See [a record of what persists](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records). - `world.LoadEntitiesInto(input, entities)` loads such a save onto entities that exist already: the i-th saved entity's components are added to or replace those of the i-th entity, each entity moving table at most once, with indexes, groups, change tracking and `EntityId` fields following. See [a record of what persists](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records). - A component renamed or moved to another namespace keeps its saves with `[NinoFormerName("Old.Name")]`: saves record types by their Nino type id. See [when the code changed](https://ecs.xgamedev.net/en/docs/guide/saves#versioning). - An unmanaged `[NinoType]` component is written by its Nino formatter, so a `VersionTolerant` or `Keyed` one may gain members between builds and still load its old rows. See [when the code changed](https://ecs.xgamedev.net/en/docs/guide/saves#versioning). - A refused load names the cause and the fix: raw rows against a formatter, a changed size or layout, two types of the process sharing an id. See [why a save does not load](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#save-refused). ### Performance - A `DynamicBuffer` that dies (its entity destroyed, the component removed) hands its emptied list to the next buffer of its element type the thread creates: entities that come and go with buffers allocate nothing once warm. See [dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers#what-it-costs) and [decision D32](https://ecs.xgamedev.net/en/docs/decisions#d32-the-lists-of-dead-buffers-are-pooled-per-thread). ### Changes that need code changes - Saves written by 4.3 or earlier do not load (`InvalidDataException`): write again the data that must outlive the upgrade. See the [migration guide](https://ecs.xgamedev.net/en/docs/migration#v4-4-saves). - EasyEcs builds on Nino 4.0.0-rc.6: reference `Nino.Generator` 4.0.0-rc.6. See the [migration guide](https://ecs.xgamedev.net/en/docs/migration#v4-4-nino). - An unmanaged component marked `[NinoType]` is saved by its formatter instead of as raw rows; remove the attribute where raw rows are meant. See the [migration guide](https://ecs.xgamedev.net/en/docs/migration#v4-4-ninotype). ### Fixes - [EECS033](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs033) no longer suggests a generated member the receiver does not have (`entity.Read()` was told to become `entity.ChildOf`, a member of query items, which does not compile). ## 4.3.0 ### New - Performance rules in the analyzer, for code that works but does more than it needs. Warnings, for code that costs: [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) a `ref` / `Span` parameter, `Get()` or `WriteX()` that only reads, [EECS026](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs026) a `[ForEach]` parameter the method does not use, [EECS027](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs027) a component or singleton looked up through the visited `Entity` or the `World` on every row, [EECS028](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs028) an allocation in a `[ForEach]` method or `OnUpdate`, [EECS029](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs029) an instance `[ForEach]` method that uses nothing of its system, [EECS030](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs030) a structural change entity by entity over a query, [EECS031](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs031) entities created one by one in a counted loop, [EECS032](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs032) `Count() > 0` instead of `Any()` and counting or filtering in a loop. Suggestion (Info), for the same cost written shorter: [EECS033](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs033) a generic call with a generated member of the same meaning (`entity.Get()` as `entity.Position`). Error: [EECS034](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs034) a system that calls `World.Update()`. Why each rule is in and the ones left out: [decision D29](https://ecs.xgamedev.net/en/docs/decisions#d29-performance-rules-only-where-the-cost-is-measured-and-the-fix-does-the-same). - Code fixes for the new rules where the change is mechanical: `in`, `ReadOnlySpan`, `Read()`, `[With]`, `static`, the bulk call (`SetAll`, `RemoveAll`, `DisableAll`, `EnableAll`, `DestroyEntities`), `CreateEntities` or `EnsureCapacity`, `Any` / `Count`, and the generated member. Each is offered only when the result compiles. - Every analyzer diagnostic links its section of the [analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer) page. ### Changes that need code changes - A build that treats warnings as errors fails on the new warnings (EECS025 to EECS032) until the code is changed or the rule is suppressed, and a system that calls `World.Update()` no longer builds (EECS034). See the [migration guide](https://ecs.xgamedev.net/en/docs/migration#v4-2-to-v4-3). ## 4.2.0 ### New - `world.EnsureCapacity(count)` pre-sizes the table of exactly those components and the entity storage, so the next `count` `CreateEntity` / `CreateEntities` calls with them never grow either (Friflo's `archetype.EnsureCapacity`, Arch's `EnsureCapacity(signature, n)`). See [structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes#bulk). ### Performance - Creating many entities in a fresh world no longer sets off a full garbage collection inside the call: a reservation (`EnsureCapacity`, `EnsureEntityCapacity`, `CreateEntities`, `InitialEntityCapacity`) grows the table and the entity storage to what it needs instead of the next power of two, and large entity storage sized by one goes to the pinned object heap, beside the columns. See [decision D28](https://ecs.xgamedev.net/en/docs/decisions#d28-reservations-grow-to-what-they-need-entity-storage-on-the-pinned-heap). ### Changes that need code changes - A `[ForEach]` method's singleton parameter throws `InvalidOperationException` when the world has no such singleton, like `world.X` and `GetSingleton()` (it used to add the default value); `world.SingletonRef()` throws the same way. Add the singleton where the world is built, before the first `Update()`: `world.SetClock(…)` or `world.AddSingleton()`, or `world.GetOrAddClock()` where the default is right. See [singletons](https://ecs.xgamedev.net/en/docs/guide/singletons#in-systems) and the [migration guide](https://ecs.xgamedev.net/en/docs/migration#v4-1-to-v4-2). ### Fixes - A `[ForEach]` method with a parameter named `owner` no longer fails to build with CS0100 in generated code. - `world.EnsureCapacity(prefab, count)` called while a query or `[ForEach]` pass walks the table it grows no longer leaves the pass writing to the old columns for the rest of the table. See [structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes#refs-across-a-change). ## 4.1.0 ### New - Archetype tables: each table stores its components as columns of rows, unmanaged columns pinned and 64-byte aligned. Removing a component keeps the row and clears a presence bit, so states that come and go never move data. See [architecture](https://ecs.xgamedev.net/en/docs/architecture). - Immediate structural changes with stricter iteration: a pass visits each entity at most once, and `ref` writes of a `[ForEach]` method survive the body's own structural changes. See [structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes). - Batch `[ForEach]` methods taking `Span` / `ReadOnlySpan` (whole runs of rows, with an `EntitySpan`), and `[ForEach(Parallel = true)]` to split one method's rows over threads without allocating. See [systems](https://ecs.xgamedev.net/en/docs/guide/systems) and [threading](https://ecs.xgamedev.net/en/docs/guide/threading). - Static `[ForEach]` methods outside systems, generic systems and runners, filters on system groups, `Maybe` parameters, `UpdatePhase`, and systems need no `partial`. See [systems](https://ecs.xgamedev.net/en/docs/guide/systems). - Ordering by dependency with `[UpdateBefore]` / `[UpdateAfter]`; errors as data with `SystemErrorPolicy.Disable` and `system.Error`; per-system timing with `WorldOptions.MeasureSystems` and `system.Stats`. See [systems](https://ecs.xgamedev.net/en/docs/guide/systems). - Change tracking (`ITrackChanges`, `[Changed]`, `QueryFilter.Changed(since)`) and removal detection (`[Removed]`, `QueryFilter.Removed(since)`). See [change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking). - Generated members for every component, tag, singleton, index, buffer and query shape: `hero.Position.X += 1`, `hero.SetVelocity(1, 0)`, `hero.SetDead()`, `world.Battle.Tick++`, `world.ZoneIndex.Find(3)`, `item.Position`, `prefab.SetLoot(…)`. See [entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components). - Prefabs (`new Prefab()`, derived prefabs, groups with `AddMember`), `world.Instantiate`, `EnsureCapacity` and `entity.Clone()`. See [prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs). - `DynamicBuffer`: a list per entity held as a tracked component. See [dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers). - Value indexes (`IIndexed`, `world.Index()`), ordered walks (`Range`, `Ascending`), relations (`IRelation` buffers) and target policies (`WhenTargetDestroyed`). See [indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations). - Hierarchies: `ChildOf(EntityId Parent)`, children, destroy cascades. See [hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy). - `GroupBy()` splits tables by a value, so a query for one zone walks only its tables. See [groups](https://ecs.xgamedev.net/en/docs/guide/groups). - `entity.Disable()` / `Enable()` and cleanup components (`ICleanupComponent`). See [cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable). - Bulk `SetAll` / `RemoveAll` / `DisableAll` / `EnableAll`, and `CreateEntities` / `DestroyEntities`. See [bulk changes](https://ecs.xgamedev.net/en/docs/guide/bulk). - Snapshots: `world.Capture()` / `world.Restore(snapshot)`. See [snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots). - Saves: `world.Save` / `Load` through Nino. See [saves](https://ecs.xgamedev.net/en/docs/guide/saves). - `SaveEntities` / `LoadEntities` / `MoveEntities` hand a group of entities to another world or process, and `world.RemoveTypes(assembly)` takes a plugin's types out of a world so its `AssemblyLoadContext` can unload. See [migration and unload](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload). - `WithAny` filters, `entity.Read()` and `entity.TryGetRef(out found)`. See [queries](https://ecs.xgamedev.net/en/docs/guide/queries). - `world.Describe()`, `entity.Describe()` and a debugger view of entities. See [API](https://ecs.xgamedev.net/en/docs/api). - Analyzer rules up to EECS024 and code fixes for them, bundled in the package. See [analyzer](https://ecs.xgamedev.net/en/docs/guide/analyzer). - Templates: `dotnet new install EasyEcs.Templates`. See [getting started](https://ecs.xgamedev.net/en/docs/getting-started). ### Performance - A realistic server tick of 100,000 entities runs much faster than in 4.0.1 and allocates nothing. See [performance](https://ecs.xgamedev.net/en/docs/performance). - Structural changes check a plain owner flag instead of a compare-and-swap, so creating and destroying entities is faster. - Jobs that cannot change structure iterate with no per-entity bookkeeping. - Parallel runs use the thread pool and wake helper threads only when they pay ([D22](https://ecs.xgamedev.net/en/docs/decisions#d22-parallel-runs-use-the-thread-pool-and-wake-helpers-only-when-they-pay)). - Change and removal summaries per block of rows ([D23](https://ecs.xgamedev.net/en/docs/decisions#d23-change-summaries-per-block-removals-summarized-apart)), index keys as id arrays ([D24](https://ecs.xgamedev.net/en/docs/decisions#d24-an-indexs-key-holds-its-entities-in-one-array)) and structural loops compiled for tables without tombstones ([D25](https://ecs.xgamedev.net/en/docs/decisions#d25-structural-row-loops-are-compiled-for-tables-without-tombstones)). - A `QueryFilter` holds no object reference, so building one at the call is cheaper ([D18](https://ecs.xgamedev.net/en/docs/decisions#d18-no-interceptors-for-query-calls-filters-carry-no-references)). - Counting rows by their set bits with `Vector512` / `Vector` ([D21](https://ecs.xgamedev.net/en/docs/decisions#d21-net-10-features-only-where-they-measure)). ### Changes that need code changes Every step is in the [migration guide](https://ecs.xgamedev.net/en/docs/migration#v4-0-to-v4-1). - `WorldOptions.Parallel` is `WorldOptions.ParallelSystems`: write `new WorldOptions { ParallelSystems = true }`. - `Entity.Id` is an `EntityId` and `Entity.Version` is gone: read `entity.Id.Index` and `entity.Id.Version`, and store `EntityId`s in components (EECS017 warns about `Entity` fields). - `EcsSystem.Priority` is gone: order systems with `[UpdateBefore]` / `[UpdateAfter]`. - The `World.SystemError` event is gone: use `new WorldOptions { SystemErrors = SystemErrorPolicy.Disable }` and read `system.Error`. - `world.DestroyEntity(entity)` is gone: call `entity.Destroy()`. - `entity.Add()` is gone: write `Set(new T(…))` or the generated `SetX(…)` to add or replace, `GetOrAdd()` to add a default only when missing. - `world.CompactArchetypes()` and `world.GetFragmentationStats()` are gone: tables stay dense on their own. - `IForEach` jobs receive only the components: take the entity through `IForEachEntity`. - `Query` results are ref structs: no `await` in the loop, no storing items in fields, lambdas or LINQ. - Structural changes belong to the world's owner thread; one made inside a parallel stage or a parallel `[ForEach]` throws `InvalidOperationException`. See [threading](https://ecs.xgamedev.net/en/docs/guide/threading). - EECS007 (state in a system) and EECS008 (a system referencing a system) are errors; they were warnings in 4.0. Move the state into a component or singleton, and let systems communicate through data. - `QueryEnumerator.Count` and `IsEmpty` are gone: call `world.Count<…>(filter)` / `world.Any<…>(filter)`. - `UpdateInterval` and `UpdatePhase` should return constants: EECS018 warns when they do not. - Refs into a table can be invalidated by structural changes of other entities; iteration order follows table rows; `AddSingleton` resets an existing singleton in place; stale handles answer `Has` / `TryGet` with false. See [refs and await](https://ecs.xgamedev.net/en/docs/guide/refs-and-await). ### Fixes - `Entity.GetHashCode()` is deterministic across runs, computed from the entity's index and version. - The analyzer knows generated writers by their symbols: a component named `Settings`, read through `entity.Settings`, no longer hides an EECS013. ## 4.0.1 ### New - `WorldOptions.Parallel` runs systems side by side when their generated read/write sets do not conflict, with the same result as running them in order. See [threading](https://ecs.xgamedev.net/en/docs/guide/threading). - A `[ForEach]` method may take no component when a `[With]` names what to query: `[ForEach, With] static void Remove(Entity e)`. See [systems](https://ecs.xgamedev.net/en/docs/guide/systems). ## 4.0.0 ### New - A rewrite for .NET 10 in one `EasyEcs` namespace: `World`, `Query`, and a single version-checked `Entity` handle whose accessors return `ref T`. - Synchronous `EcsSystem`s with source-generated `[ForEach]` methods, system groups with `[UpdateInGroup]`, recycled entity ids and per-world singletons. - An analyzer that enforces the ECS principles (EECS006-EECS008). See [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles). ### Changes that need code changes Every rename is in the [migration guide](https://ecs.xgamedev.net/en/docs/migration#v3-to-v4-0). - `Context` is `World` and `GroupOf` is `Query`. - Systems are synchronous: no UniTask, no async callbacks. - Events are gone: state changes are components. ## 3.1.1 ### Fixes - The release build uses the .NET 8 SDK (C# 13); the library is unchanged. ## 3.1.0 ### New - `Count` and `IsEmpty` on `GroupResultEnumerator`, and `CountOf()` / `AnyOf()` on `Context`. - `Tag.SetBits` / `ClearBits` take a `params ReadOnlySpan`. ### Performance - `Tag.ContainsAll` matches archetypes with SIMD. - `GetFragmentationStats` is lock-free, and `Update()` reuses its task buffer. - Archetypes are walked by index instead of by dictionary enumeration. ### Fixes - `Avx2.TestZ` corrected to `Avx.TestZ`. ## 3.0.5 ### Performance - No state machine cost for tasks that already completed. ## 3.0.4 ### Performance - Tiny tasks run inline instead of on the thread pool. ## 3.0.3 ### Performance - Parallel work uses an array pool instead of materializing UniTasks. ## 3.0.2 ### Performance - Faster `GetMatchingArchetypes`. ## 3.0.1 ### Fixes - A repeat of the 3.0.0 release with the same contents. ## 3.0.0 ### New - Archetypes, and adding or removing several components in one call. ### Performance - Entity creation and destruction and component changes take effect at once. - Faster `GroupOf` and tags, with better locality. ### Changes that need code changes - Callbacks are gone and changes run at once. See the [migration guide](https://ecs.xgamedev.net/en/docs/migration#v2-to-v3-0). ## 2.1.6 ### Performance - Iterating systems allocates nothing. ## 2.1.5 ### Performance - Getting groups allocates nothing (no red-black tree). ## 2.1.4 ### Performance - Faster `Update`. ## 2.1.3 ### Performance - Every overload of `GroupOf` allocates nothing. ## 2.1.2 ### Performance - Faster task scheduling. ## 2.1.1 ### Performance - Faster task dispatching. ## 2.1.0 ### Performance - Singleton components allocate less. ## 2.0.10 ### Performance - A better resize strategy. ## 2.0.9 ### Performance - Faster component lookup. ## 2.0.8 ### Performance - Faster entity and component lookup. ## 2.0.7 ### Performance - No `SortedList` needed. ## 2.0.6 ### Performance - Fewer allocations through `ValueTask`. ## 2.0.5 ### Fixes - Several bugs fixed. ## 2.0.4 ### Fixes - A tag type is registered automatically on first use. ## 2.0.3 ### Fixes - The `AddSingletonComponent` callback passes a `ref`. ## 2.0.2 ### Performance - Better memory use. ## 2.0.1 ### Performance - Faster iteration, refs, entity creation and component adds. ## 2.0.0 ### New - A lock-free context for parallel systems, components that allocate nothing, faster component lookup. ## 1.0.8 ### Changes that need code changes - Initializing a context no longer catches exceptions. ## 1.0.7 ### Changes that need code changes - Components are classes that hold a reference to their entity. ## 1.0.6 ### New - An entity gives access to its context. ## 1.0.5 ### New - `SingletonComponent`: a context holds any number of them. ## 1.0.4 ### New - Systems run in parallel. ## 1.0.3 ### Fixes - Several systems with the same priority all run. ## 1.0.2 ### New - Get an entity from a context by its id. ## 1.0.1 ### New - Systems can be added after the context has been initialized. ## 1.0.0 ### New - The first release: an ECS with asynchronous, parallel systems. --- # Migration guide > Upgrade EasyEcs one version step at a time: what to change in your code from v2 to v3, v3 to v4 and between 4.x releases, with code before and after. URL: https://ecs.xgamedev.net/en/docs/migration Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/migration.md What to change in your code when you upgrade EasyEcs, one version step per section, newest first. Each section lists every rename, removal and behavior change of its step, with the code to write instead. Upgrading across several versions? Apply the sections in order, oldest first. The [changelog](https://ecs.xgamedev.net/en/docs/changelog) lists everything each release added; the [API reference](https://ecs.xgamedev.net/en/docs/api) is the current API. ## v4.3 → v4.4 The save format changed, and EasyEcs builds on Nino 4.0.0-rc.6. Code written for 4.3 compiles unchanged; what needs attention is saved data and the Nino package reference. ### Saves of 4.3 and earlier do not load A save now records each type by its Nino type id instead of its name, and writes unmanaged `[NinoType]` components through their formatter. `Load`, `LoadEntities` and `LoadEntitiesInto` refuse the bytes of an earlier version with `InvalidDataException: Not an EasyEcs save (or one of another format version)`, and leave the world as it was. Write again what must outlive the upgrade: load it with the 4.3 build, move it into a format of your own (or keep the 4.3 build as the tool that reads it), and save it with 4.4. Saves that only live as long as a process (hot reload, handing a player to another server of the same build) need nothing. ### Nino 4.0.0-rc.6 EasyEcs references `Nino.Serialization` 4.0.0-rc.6. A project that generates formatters references the same version of `Nino.Generator`: **4.3** ```xml ``` **4.4** ```xml ``` ### Unmanaged `[NinoType]` components are written by Nino An unmanaged component marked `[NinoType]` was saved as raw rows, like any unmanaged component. It is now written by its Nino formatter, value by value, so its format decides how it may change between builds ([when the code changed](https://ecs.xgamedev.net/en/docs/guide/saves#versioning)). Keep the attribute where the shape will change; remove it where raw rows (one block per column) are what you want: **4.3** ```csharp [NinoType] public partial record struct Speed(float Value) : IComponent; // saved as raw rows ``` **4.4** ```csharp using Nino.Core; public record struct Speed(float Value) : IComponent; // raw rows [NinoType(format: NinoFormat.VersionTolerant)] public partial record struct Rank(int Tier, int Points) : IComponent; // by its formatter: may gain members ``` ## v4.2 → v4.3 The analyzer gained performance rules ([EECS025 to EECS034](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025)). Code written for 4.2 compiles unchanged unless a system calls `World.Update()`, or the build treats warnings as errors. ### New warnings: EECS025 to EECS032 Each names code that works but costs, with the fix in its [section of the analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer) and, where the change is mechanical, a code fix in the IDE. Apply the fix, or suppress the rule where the code is deliberate, with the reason next to it. With a tracked `Armor` and a `Seen` counter: ```csharp public record struct Armor(int Value) : IComponent, ITrackChanges; public record struct Seen(int Count) : IComponent; ``` ```csharp #pragma warning disable EECS026 // the write access is the point: it stamps the rows a [Changed] system reacts to [ForEach] static void Touch(ref Armor armor, ref Seen seen) => seen.Count++; #pragma warning restore EECS026 ``` Or turn a rule down for a whole project in `.editorconfig`: ```ini dotnet_diagnostic.EECS028.severity = suggestion ``` ### `World.Update()` in a system is an error: EECS034 It ran the system again inside its own run. Run updates and groups from the code that hosts the world. **4.2** ```csharp public class CatchUp : EcsSystem { protected override void OnUpdate() => World.Update(); } ``` **4.3** ```csharp while (running) world.Update(); // in the host loop ``` ### The suggestion EECS033 EECS033 shows in the IDE only and never fails a build: the generated member is the same call at the same cost, only shorter. `dotnet_diagnostic.EECS033.severity = warning` in `.editorconfig` turns it into a warning. ## v4.1 → v4.2 One behavior changed; code written for 4.1 compiles unchanged. ### A missing singleton throws in `[ForEach]` methods A `[ForEach]` singleton parameter resolves through `world.SingletonRef()`, which used to add the singleton with its default value. Both now throw `InvalidOperationException`, like `world.X` and `GetSingleton()`, on the system's first run, even when no entity matches. The message names the fix: ```text Singleton Clock was not added to this world: set it before the systems that read it run (world.SetClock(...) or world.AddSingleton()), or use GetOrAddClock() where a default is meant ``` Add every singleton your systems read where the world is built, before the first `Update()`, also in tests. With this singleton and system: ```csharp public record struct Clock(long Tick, float DeltaTime) : ISingletonComponent; public class Ticker : EcsSystem { [ForEach] static void Advance(in Clock clock, ref Position position) => position.X += clock.DeltaTime; } ``` **4.1**: the first update added a default `Clock`, with no step. ```csharp var world = new World(); world.AddSystem(); world.Update(); ``` **4.2**: set it first, or call `world.GetOrAddClock()` where the default is right. ```csharp var world = new World(); world.SetClock(Tick: 0, DeltaTime: 1f / 30); world.AddSystem(); world.Update(); ``` A world restored with `Load` already holds the singletons of its save; add only the ones the save did not hold. See [singletons in systems](https://ecs.xgamedev.net/en/docs/guide/singletons#in-systems). ## v4.0 → v4.1 A few APIs changed (listed first). Other code written for 4.0 compiles unchanged unless it stores `Query` results in fields, uses them across `await`, captures them in lambdas, uses them in iterators or LINQ, or passes them as generic arguments: they are ref structs now. The storage moved from one column per component type (indexed by entity id) to archetype tables (one row per entity, columns 64-byte aligned), which changes a few behaviors. ### Renamed and removed APIs - **`WorldOptions.Parallel` is `WorldOptions.ParallelSystems`.** The option runs systems side by side; the new name keeps it apart from `[ForEach(Parallel = true)]`, which splits one method's rows over threads. Rename the initializer: `new WorldOptions { ParallelSystems = true }`. - **`Entity.Id` is an `EntityId`** (index + incarnation, 8 bytes, unmanaged) instead of an `int`, and the `Entity.Version` field is gone: read `entity.Id.Index` and `entity.Id.Version`. `world.GetEntity`, `TryGetEntity` and `IsAlive` take an `EntityId`; a handle converts to one implicitly, so `world.GetEntity(entity)` compiles. Store `EntityId`s, not `Entity` handles, in components: a handle holds its world, which makes the column managed (scanned by the GC, not copied as a block, not serializable), and the new warning [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) points at such fields. - **`EcsSystem.Priority` is gone.** Systems run in registration order; order them by what they depend on with `[UpdateBefore]` / `[UpdateAfter]` on the class. A cycle is [EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019), an order against a system of another group [EECS020](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs020). - **The `World.SystemError` event is gone.** A system's exception propagates out of `Update` (the default), or, with `new WorldOptions { SystemErrors = SystemErrorPolicy.Disable }`, switches the system off and stays in `system.Error` for the application to read from `world.Systems`. Enable the system again to retry. - **Systems need no `partial`.** The generated code lives outside the system's type, so EECS001 is gone; `partial` still compiles. - **`UpdateInterval` and the new `UpdatePhase` should be constants**: they are read every update, and the warning [EECS018](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs018) points at overrides that compute them. To stop and resume a system, set `Enabled`. - **`world.DestroyEntity(entity)` is gone**: it did what `entity.Destroy()` does. Call `entity.Destroy()`, or `world.DestroyEntities(filter)` for every match at once. - **`IForEach` jobs receive only the components.** `Execute(int entityId, ref T1 c1, …)` became `Execute(ref T1 c1, …)`, so a pass never loads the entity rows for them. A job that needs the entity implements `IForEachEntity<…>` (`Execute(Entity entity, ref T1 c1, …)`) and runs with `world.ForEachEntity`. - **`CompactArchetypes()` and `GetFragmentationStats()` are gone.** Tables stay dense on their own, and passes now end even when a job throws, so there is nothing to compact and nothing to monitor (the ratio was always 0 between updates). Delete the calls. - **`entity.Add()` is gone.** It did what `Set` and `GetOrAdd` do, and reset a component the entity already had, unlike adding in other ECS libraries. Write the generated `entity.SetX(…)` (`SetDead()` for a tag) or `entity.Set(new T(…))` to add or replace a value, and `ref var c = ref entity.GetOrAdd()` to add a default value only when it is missing and fill it through the ref. - **`world.Systems` is a `SystemList`** (allocation-free `foreach` and `Count`) instead of a new `IReadOnlyList`; `foreach` loops compile unchanged. - **`QueryEnumerator.Count` / `IsEmpty` are gone**: use `world.Count` / `world.Any` with the same filter. - **`entity.Remove<…>()` returns the entity** for chaining; calls that ignore it compile unchanged. - **`RemoveSingleton()` returns `bool`** (false when the singleton was not added). Calls that ignore the result compile unchanged. ### Behavior changes - **Stale and `default` handles answer questions with false.** `Has()` and `TryGet()` used to throw for a destroyed entity (and `default(Entity).Has()` threw a `NullReferenceException`); they now return false, like `IsAlive`. `Get`, `GetOrAdd`, `Set` and `Remove` still throw, now `InvalidOperationException` for `default` handles too. - **Structural changes belong to the world's owner thread.** 4.0 serialized creates, destroys, `Add` / `Set` / `Remove` and singleton or system changes from any thread with a compare-and-swap lock. 4.1 checks a plain owner flag instead: a change made while another runs, or inside a parallel stage of systems or a parallel `[ForEach]`, throws `InvalidOperationException`; two threads of your own changing one world at once are not caught reliably. Make structural changes on the thread that calls `Update` (other threads hand them over as data through a queue a system drains: [input from other threads](https://ecs.xgamedev.net/en/docs/guide/threading#input-from-other-threads)), or give each thread its own world. Two analyzer errors point at such code: [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013), a structural change in a `[ForEach]` method that takes no `Entity` or `World` (for example through a handle a component holds: take the `Entity` as a parameter), and [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014), a structural change in a lambda handed to `Task.Run`, `Parallel.*`, `ThreadPool` or a `Thread` that races with other changes of the same world. - **EECS007 and EECS008 are errors.** Mutable state in a system ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007)) and a system referencing a system ([EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008)) were warnings in 4.0; code that triggers them no longer builds. Move the state into a component or singleton, and communicate through data. Every rule of 4.1 is an error except the warnings EECS017, EECS018 and EECS020 named above. - **Iteration semantics are stricter.** A pass visits each entity at most once: entities created or moved into a matching archetype during the pass are not visited by it (one that only gets a queried component back keeps its row and is visited if the pass has not reached it); entities destroyed or losing a queried component before their turn are skipped. `Without` filters that only existed to stop a job from revisiting what it produced are no longer needed (they still work). - **Refs move more often.** A `ref` from `entity.Get()` or a `Query` item can now be invalidated by a structural change of *another* entity (a row filled by a table's last row, a table that grows), not only by entity-capacity growth. The documented rule was already "a ref is valid until the next structural change"; code that relied on refs surviving changes must re-read through `entity.Get()`. The `ref` parameters of `[ForEach]` methods and `ForEach` jobs stay writable when the body changes the visited entity's archetype. See [refs and await](https://ecs.xgamedev.net/en/docs/guide/refs-and-await). - **Removing a component keeps the entity's row.** `Has()`, `Get()` and every query treat the component as absent; adding it back is a bit flip. - **`Query` results are ref structs.** `QueryEnumerator<…>` and `QueryItem<…>` hold refs into the current table, so a `foreach` over a query cannot contain an `await` and an item cannot be stored. Read what you need, or keep `item.Entity`, then await outside the loop. - **Iteration order** follows table rows, not entity ids, and can change when rows are moved or filled. Never rely on it. - **`EnsureEntityCapacity` / `InitialEntityCapacity`** pre-size the entity records only; archetype tables grow on their own. - **`ParallelSystems` keeps subclasses it cannot see alone.** A system class that derives from a generated system without adding `[ForEach]` methods of its own (for example to override `OnUpdate`) now runs alone (it never shares a stage with another system), as its `OnUpdate` may touch anything. Give the subclass a `[ForEach]` method (it is then generated) to run it beside others again. - **`AddSingleton()` on an existing singleton resets it in place.** It used to replace the storage, which left `SingletonRef` handles taken before pointing at a detached copy; they now see the reset value. - **`Entity.GetHashCode()` is deterministic** (`Index ^ (Version << 20)`) instead of `HashCode.Combine` (randomized per process). Equality is unchanged; only code that persisted hash codes across processes could notice. ### New in 4.1 - `[ForEach]` methods can take `Span` / `ReadOnlySpan` components (plus singletons) and receive whole runs of rows, for SIMD ([EECS009](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs009) reports mixed signatures). The ad-hoc form is `world.ForEachBatch` with an `IForEachBatch` job. - `world.ForEachEntity` with an `IForEachEntity` job receives the `Entity` handle instead of the id. - `INoStructuralChanges` marks a job that makes no structural change; the generator adds it to `[ForEach]` methods that cannot change structure, which then iterate without per-entity bookkeeping. - `QueryFilter.WithAny()` and `[WithAny]`: the entity needs at least one of the named components. - `world.CreateEntities(span, components…)` and `world.DestroyEntities(filter)` spawn and clear waves with one pass through the structural gate. - `WorldOptions.MeasureSystems` times every system run into `system.Stats` (`SystemStats`). - `[ForEach(Parallel = true)]` (and `world.ForEachParallel` / `ForEachEntityParallel`) runs chunks of `World.ParallelChunkRows` rows on several threads; [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) reports methods that could race. - `world.Capture()` / `world.Restore(snapshot)`: in-memory snapshots of entities, components and singletons ([snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots)). - `ITrackChanges`, `[Changed]`, `QueryFilter.Changed(since)` / `Since(since)`, `world.ChangeTick`, `system.LastRunTick`: change tracking ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking)). The job interfaces gained an optional static `Writes` member (with a default). - `[Removed]` and `QueryFilter.Removed(since)`: the entities that lost a tracked component since a tick (replication of what went away), with [EECS016](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs016) for filters no row can pass. - `Prefab` and `world.Instantiate(prefab)` / `Instantiate(prefab, span)`: entities from a recipe of components that belongs to no world, built with `Set` / `Remove` or the generated `prefab.SetX(…)` / `RemoveX()` (chainable), and `SetBuffer(…)` / `SetLoot(…)` for the elements of a `DynamicBuffer`; `entity.Clone()` copies a living entity. - `IIndexed`, `world.Index()`, `ValueIndex`: find entities by a component value; relations are indexed `Entity` keys ([indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations)). - `entity.Read()` returns a `ref readonly T` that never counts as a write of a tracked component, and `entity.TryGetRef(out bool found)` returns a `ref T` (a null ref when missing): optional access without a copy. `entity.Has()` tests several components with one lookup. - `DynamicBuffer`: a list per entity as a component, written only through `ref` (each write is a tracked change), copied by snapshots ([dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers)). - [EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) rejects a `[ForEach]` method that changes a collection or class held by an `in` parameter (the change would be neither scheduled as a write nor tracked); [EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012) rejects a `DynamicBuffer` copied by value. - The library is marked `IsAotCompatible`: trimming and Native AOT analyzers run on every build, and it publishes and runs with Native AOT. - `entity.Disable()` / `Enable()` (generated `DisableX()` / `EnableX()` / `IsXDisabled`): switch a component off and keep its value; queries see `Disabled`. `world.SetAll` / `RemoveAll` / `DisableAll` / `EnableAll` change every entity a filter matches, 64 rows at a time. - `ICleanupComponent`: destroying an entity that holds one keeps it, tagged `Destroyed`, until a system releases what it holds and removes the last cleanup component. - `ChildOf(EntityId Parent)` and `world.Children(parent)`: a hierarchy whose parents destroy their children; `IRelation` elements of a `DynamicBuffer` (`entity.AddRelation`, `world.Relations()`) link an entity to any number of targets, and `TargetRules` say what happens to links when a target is destroyed. - Ordered walks of a value index with a comparable key (`Range`, `RangeDescending`, `Ascending`, `Descending`), and `world.GroupBy()`, which splits tables by the value of an `IGroup` component. - `Maybe` parameters of `[ForEach]` methods: an optional component without a second method. - `world.Save` / `world.Load` (a world as bytes, through Nino), `SaveEntities` / `LoadEntities` / `MoveEntities` (a group of entities to another world or process, `EntityId` fields rewritten), `world.Capture(into)` (reuses an earlier snapshot's arrays). - `world.RemoveTypes(assembly)`: unload game logic loaded into a collectible `AssemblyLoadContext`; its systems, singletons, indexes and components leave the world, and the process forgets its types once it unloads. - `world.Describe()` (tables, columns, sizes), `entity.Describe()` and a debugger view of entities. - Static `[ForEach]` methods outside systems (a generated entry point takes the `World` and the method's other arguments: one pass for tools and tests), generic systems, filters on system groups (`[With]` on a group struct applies to all its systems), `UpdatePhase` to spread systems with the same `UpdateInterval` over updates, `world.GetOrAddX()` for singletons, named query items (`item.Position` for `item.Component1`), code fixes for the analyzer's diagnostics, and [EECS024](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs024) for `[ForEach]` on a local function. ## v3.x → v4.0 v4 targets **.NET 10 only**, moves the whole API into the `EasyEcs` namespace with standard ECS vocabulary, makes systems synchronous and generates the repetitive parts (arity overloads, per-entity jobs). ### Namespaces `EasyEcs.Core`, `EasyEcs.Core.Components` and `EasyEcs.Core.Systems` become one namespace: `using EasyEcs;`. ### Entities and components v3 had three handle types (`Entity` value, `EntityRef`, `ComponentRef`). v4 has one: `Entity`, a version-checked 16-byte handle. Component access returns `ref T` directly. Since 4.1 the generator also writes a named member for each component (`e.Position`, `e.SetPosition(…)`, `e.HasPosition`), which current code prefers over the generic calls in this table ([generated members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members)). | v3 | v4 | | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `Context` | `World` | | `EntityRef e = ctx.CreateEntity()` | `Entity e = world.CreateEntity()` or `world.CreateEntity(new Position(..), new Velocity(..))` | | `e.Value.AddComponent().Value.X = 1` | `e.GetOrAdd().X = 1` (`ref T`), or `e.Set(new T(..))` | | `e.Value.AddComponents()` | `e.Set(new A(..), new B(..))` (add or overwrite values, one transition) | | `e.Value.GetComponent().Value` | `e.Get()` (`ref T`) | | `e.Value.TryGetComponent(out ComponentRef r)` | `e.TryGet(out T value)` / `ref var x = ref e.GetOrAdd()` | | `e.Value.HasComponent()` | `e.Has()` | | `e.Value.RemoveComponent(s)<..>()` | `e.Remove<..>()` | | `ctx.DestroyEntity(e)` | `e.Destroy()` | | `ctx.GetEntityById(id)` / `TryGetEntityById` | `world.GetEntity(id)` / `TryGetEntity` | | `ctx.AllEntities` | `world.Entities` | | `ctx.GroupOf()` → `GroupResult` | `world.Query(filter)` → `QueryItem` (`item.Entity`, `item.Component1..n`) | | `ctx.CountOf()` / `AnyOf()` | `world.Count(filter)` / `world.Any(filter)` | | `new Context(new Context.Options(parallel, levels, capacity))` | `new World(new WorldOptions { ParallelSystems = .., MaxDegreeOfParallelism = .., InitialEntityCapacity = .. })` (parallel is **off** by default) | ### Singletons | v3 | v4 | | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------- | | `AddSingletonComponent()` / `GetSingletonComponent().Value` | `AddSingleton()` / `GetSingleton()` / `GetOrAddSingleton()` (all `ref T`) | | `TryGetSingletonComponent(out SingletonComponentRef)` | `TryGetSingleton(out T value)` | Singletons are now **per world** (v3 shared them process-wide). A `[ForEach]` method takes a singleton as a `ref` / `in` parameter (resolved once per pass), so systems rarely call `GetSingleton` themselves. ### Systems v3 systems implemented `IInitSystem` / `IExecuteSystem` / `IEndSystem` with `UniTask` methods. v4 systems derive from `EcsSystem` and override synchronous hooks; the UniTask dependency is gone. **v3** ```csharp public class S : SystemBase, IInitSystem, IExecuteSystem { public UniTask OnInit(Context ctx) { ...; return UniTask.CompletedTask; } public UniTask OnExecute(Context ctx) { ...; return UniTask.CompletedTask; } } ``` **v4** ```csharp public partial class S : EcsSystem { // when added to the world protected override void OnCreate() { } // every update (World property available) protected override void OnUpdate() { } // per entity, after OnUpdate [ForEach] static void Step(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y); } ``` - `ctx.Init()` is gone: `OnCreate` runs when the system is added. `await ctx.Update()` becomes `world.Update()`; `await ctx.DisposeAsync()` becomes `world.Dispose()` (`OnDestroy` in reverse order). - `IExecuteSystem.ExecuteFrequency` becomes `EcsSystem.UpdateInterval`; `AddSystem()` returns the system; `GetSystem()` and `Enabled` were added; `RemoveSystem()` now returns `bool` (whether a system was removed). - Exceptions: `world.SystemError` (system, exception); without a subscriber the exception propagates. (4.1 replaced the event, see [v4.0 → v4.1](https://ecs.xgamedev.net/en/docs/migration#v4-1-api).) ### Behavioral changes 1. **Entity ids are recycled.** `Entity.Id` is unique only among live entities; keep the `Entity` handle (id + version). Equality includes the version. 2. **Stale handles are rejected**: access and structural changes throw; `Destroy` of a stale handle is ignored. 3. **Removing a component or destroying an entity releases managed references** held by the component. 4. **Components and singletons must be structs**: the analyzer reports [EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006) for classes. 5. Never call `CompactArchetypes()` while iterating (it rewrites rows). 4.1 removed it. 6. **Systems should be stateless and independent**: the analyzer warns about mutable fields on systems ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007): move the state into a component or singleton) and about systems referencing other systems ([EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008): communicate through data). See [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles). 7. **`IEvent`, `IEventHandler` and `Publish` are removed.** Write state changes as data (a tag or a field) and let later systems query them. 8. **`ParallelSystems` is safe by construction.** v3 ran every system of one priority at once and left data races to you. v4 runs systems of one priority together only when their generated access does not conflict (`ref` = write, `in` = read); systems with an `Entity` / `World` parameter, instance `[ForEach]` methods, an `OnUpdate` override or no `[ForEach]` method run alone. The result equals a sequential update. See [threading](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems). ### Source generator and analyzer Both ship in the package (`analyzers/dotnet/cs`). A project that references `EasyEcs.Core` by `ProjectReference` must also reference `EasyEcs.Generator.csproj` with `OutputItemType="Analyzer" ReferenceOutputAssembly="false"`: ```xml ``` ## v2.x → v3.0 v3.0 was a complete redesign around **zero-allocation immediate execution** for high-performance servers: callbacks and the command buffer are gone, every operation runs at once and returns its result. The code in this section is v2 and v3 code; none of it compiles against v4. ### Breaking changes **No more callbacks.** v2 deferred every operation and handed the result to a callback; v3 executes at once and returns it. **v2** ```csharp context.CreateEntity(entity => { entity.AddComponent(pos => { pos.Value.X = 10; entity.AddComponent(vel => { vel.Value.X = 5; }); }); }); ``` **v3** ```csharp var entity = context.CreateEntity(); var pos = entity.AddComponent(); pos.Value.X = 10; var vel = entity.AddComponent(); vel.Value.X = 5; ``` | v2 | v3 | Notes | | ------------------------------------------------------- | ----------------------------------------------------- | ------------------------- | | `void CreateEntity(Action)` | `EntityRef CreateEntity()` | Returns the entity | | `void AddComponent(Entity, Action>)` | `ComponentRef AddComponent(Entity)` | Returns the component ref | | `void AddComponent(Action>)` | `ComponentRef AddComponent()` | On the `Entity` struct | | `void AddSingletonComponent(Action<...>)` | `SingletonComponentRef AddSingletonComponent()` | Returns the ref | | `void AddSystem()` | `void AddSystem()` | Unchanged (immediate) | | `void RemoveSystem()` | `void RemoveSystem()` | Unchanged (immediate) | **Execution model.** v2 queued operations into a command buffer, executed them at the end of the frame and invoked the callbacks after. v3 executes every operation at once, thread-safe through the .NET 8 `Lock`, with no command buffer and no callbacks. **Version tracking.** v3 adds a version to the entity, incremented on destroy. `EntityRef` and `ComponentRef` validate it on access and throw if the entity was destroyed. ```csharp public struct Entity { public readonly int Id; public readonly int Version; // new: increments on destroy // ... } ``` ### Migration steps #### Target .NET 8 and C# 13 C# 13 is required for ref fields and other performance optimizations. ```xml net6.0 10 ``` ```xml net8.0 13 ``` #### Replace callbacks with return values Entity creation, component addition, nested callbacks and the same in systems all become plain statements: ```csharp // v2 context.CreateEntity(entity => { entity.AddComponent(); }); entity.AddComponent(health => { health.Value.HP = 100; }); // v3 var entity = context.CreateEntity(); entity.AddComponent(); var health = entity.AddComponent(); health.Value.HP = 100; ``` #### Update singleton components ```csharp // v2 context.AddSingletonComponent(config => { config.Value.MaxPlayers = 100; }); // v3 var config = context.AddSingletonComponent(); config.Value.MaxPlayers = 100; ``` #### Keep entity destruction, iteration and systems `context.DestroyEntity(entity)` is the same in both versions, and still immediate. `GroupOf` iteration is unchanged. Systems work the same way, with the immediate API inside: ```csharp public class MovementSystem : SystemBase, IExecuteSystem { public async UniTask OnExecute(Context context) { foreach (var result in context.GroupOf()) { ref var pos = ref result.Component1.Value; ref var vel = ref result.Component2.Value; pos.X += vel.X; } } } ``` #### Add and remove several components at once New in v3.0: one archetype transition for several components, instead of one per call (two separate calls cost twice as much). Use them when you add or remove 2 or 3 components on one entity, build entities with several components, or change components often on a hot path. ```csharp var (pos, vel) = entity.AddComponents(); pos.Value.X = 10; vel.Value.X = 5; var (pos, vel, health) = entity.AddComponents(); entity.RemoveComponents(); ``` ### Modifying components and holding refs Components are structs. Write through the `ComponentRef` (`health.Value.HP = 100`) or through `ref var h = ref health.Value`; `var h = health.Value` copies the component, and the changes to the copy are lost. A `ref` stays valid only until the component arrays are resized. Component data lives in `Context.Components[typeIndex][entityId]`, and only `CreateEntity` (when the capacity is exceeded) resizes those arrays, so a `ref` held across `CreateEntity` may dangle and crash or read the wrong data. `AddComponent`, `RemoveComponent` and `DestroyEntity` only change which archetype list an entity belongs to, and `CompactArchetypes` only removes tombstones from the archetype lists: none of them moves component data, so refs survive them (destroying the entity whose component a `ref` points at is still a logic error). Singletons are stored apart and are not affected by `CreateEntity` or `CompactArchetypes`. ```csharp var health = entity.AddComponent(); ref var h = ref health.Value; h.HP = 100; // safe context.CreateEntity(); // may resize every component array h.HP = 50; // unsafe: h may point to the old array health.Value.HP = 50; // safe: the ComponentRef finds the current location ``` During `GroupOf` iteration, `DestroyEntity`, `AddComponent` and `RemoveComponent` are safe (tombstones handle them); `CreateEntity` leaves the iterator working but invalidates `ref` locals, so read through `result.Component1.Value` when the loop creates entities; `CompactArchetypes` breaks the iterator itself and must run outside the loop. Rule of thumb: when unsure, write `compRef.Value.field`, and keep `ref` for short local code that creates no entity. Adding a component or a singleton the entity or context already has erases its data (the component is reinitialized to default). Check first: ```csharp if (!entity.TryGetComponent(out var health)) { health = entity.AddComponent(); } health.Value.HP = 100; ``` ### Common patterns ```csharp // a test: no callback to wait for var entity = context.CreateEntity(); Assert.GreaterOrEqual(entity.Value.Id, 0); // an entity builder returns the entity public EntityRef SpawnEnemy(Vector2 pos) { var entity = context.CreateEntity(); entity.AddComponent().Value = pos; entity.AddComponent().Value.HP = 100; entity.AddComponent(); return entity; } // initialization and conditions are plain statements var inv = entity.AddComponent(); inv.Value.Capacity = 20; inv.Value.Items = new List(); if (isPlayer) entity.AddComponent(); ``` ### Thread safety v2's command queue was thread-safe and the callbacks ran on the main thread at the end of the frame. In v3 every operation is thread-safe through the .NET 8 `Lock`, entity id allocation is lock-free (`Interlocked`), and several threads can create and modify entities at once: ```csharp Parallel.For(0, 1000, i => { var entity = context.CreateEntity(); entity.AddComponent(); }); ``` v4.1 changed this: structural changes belong to the world's owner thread (see [v4.0 → v4.1](https://ecs.xgamedev.net/en/docs/migration#v4-1-behavior)). ### What changed for performance v2 allocated a closure on every `CreateEntity` call and four on every `AddComponent` call, so a world that kept creating entities kept producing garbage. v3 allocates nothing after warm-up: its arrays are allocated up front and grow only once, with no closures. The rest of the hot path changed too: | Operation | v2 | v3 | | ---------------------- | ------------------------- | ------------------------------------ | | Tag bitwise operations | scalar operations | one SIMD instruction | | Archetype queries | a scan of every archetype | a cached match | | Bounds checks | on every access | removed behind invariants (`Unsafe`) | For what EasyEcs measures today, see [performance](https://ecs.xgamedev.net/en/docs/performance). Iteration became safe to modify: v2 had undefined behavior when an entity changed during iteration (entities could be skipped or visited twice); v3 marks removed slots with a tombstone (-1) and reads a fresh span after a resize, so the behavior is predictable. ### New in v3.0 - **Cross-platform SIMD**: AVX2 on x86 / x64, AdvSimd (NEON) on ARM, a scalar fallback elsewhere. - **Up to 65,536 component types** (the component index became a `ushort` instead of a `byte`): the first 256 inline (32 bytes, two `Vector128`), the rest in an overflow array. - **Archetype query cache**: the first `GroupOf` of a shape builds the cache in O(N), later ones look it up in O(1). - **Manual defragmentation**: `GetFragmentationStats()` returns `(totalSlots, alive, ratio)`, and `CompactArchetypes()` removes the tombstones (during loading screens, for example when the ratio passes 0.5). - **Pre-allocation**: `new Context(new Context.Options(parallel: true, levelOfParallelism: -1, initialEntityCapacity: 10_000))` (`-1` uses all cores), and `context.EnsureEntityCapacity(100_000)` later. ### Performance tips for v3 - Pre-allocate the entity capacity: `context.EnsureEntityCapacity(expected)`. - Check fragmentation and compact between levels, outside any `GroupOf` loop: `CompactArchetypes()` invalidates `GroupOf` iterators but not component refs. - Add and remove components with `AddComponents` / `RemoveComponents`: one archetype transition instead of three. - Run systems in parallel: `new Context(new Context.Options(parallel: true))`. - Create entities in a plain loop: the lock is taken once per operation. - Modify components in place: `result.Component1.Value.X += 1`, or a `ref` local when the loop creates no entity. ### Troubleshooting v3 | Symptom | Cause | Fix | | ------------------------------------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | "Entity has been destroyed" exception | A stale `EntityRef` / `ComponentRef` used after the entity was destroyed; versioning detects it | Do not cache refs across frames; look the entity up again with `context.TryGetEntityById(id, out var entity)` | | Tests fail after the upgrade | Assertions inside callbacks | Create the entity, then assert: `var entity = context.CreateEntity(); Assert.NotNull(entity);` | | Component changes do not persist | The component value was copied to a local (structs) | Write `health.Value.HP = 100`, or through `ref var h = ref health.Value` | | Crash or corrupted data with `ref` | A `ref` held across `CreateEntity`, which may resize the arrays | Keep the `ComponentRef` and write through `.Value`; `AddComponent`, `RemoveComponent` and `CompactArchetypes` are safe with refs | | Iteration behaves differently | v3 skips tombstones of entities added or removed during iteration | Usually nothing: iteration is safe now | In short: remove every callback, use the returned values, and expect every operation to run at once, thread-safe and without allocations after warm-up. For questions, open an [issue on GitHub](https://github.com/JasonXuDeveloper/EasyEcs/issues). ## Related - [Changelog](https://ecs.xgamedev.net/en/docs/changelog): What each release added, improved and fixed. - [Analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer): Every EECS rule with its fix, including the ones an upgrade brings. - [API and complexity](https://ecs.xgamedev.net/en/docs/api): The current API, with the cost of every call. --- # Getting started > Build a small ECS simulation in C# step by step, from dotnet new console to components, tags, queries, systems, singletons, system groups and the update loop. URL: https://ecs.xgamedev.net/en/docs/getting-started Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/getting-started.md This tutorial builds a small simulation from an empty console project: a thousand units walk east, some of them are on fire, the burning ones die and their corpses are removed, and a report prints once a second. Each step adds one concept, compiles and links to the guide page that covers it in depth. It takes about fifteen minutes. You need the [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0). EasyEcs targets `net10.0` only. ## Build it step by step ### Create a project ```bash dotnet new console -n Arena cd Arena dotnet add package EasyEcs ``` The package brings the source generator, the analyzer and its code fixes with it. There is nothing to register and no `partial` to write: everything lives in the `EasyEcs` namespace. > **Other ways to start** > > - `dotnet new install EasyEcs.Templates`, then `dotnet new easyecs -n Arena` (add `--tests` for an NUnit project > with a test file per system): a fixed-tick server, ready to run, laid out the way this tutorial ends up: > `Components/`, `Systems/` with one system per file, and a `Program.cs` that only hosts the world. Inside the > project, `dotnet new easyecs-system -n RegenSystem -o Systems` adds a system > ([templates](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/templates)). > - Complete programs to read, from the smallest up: > [`samples/`](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples), starting with HelloWorld. ### Define components and tags A component is a plain struct implementing `IComponent`: fields, no logic. A struct with no fields is a **tag**, a yes-or-no state that systems filter on. Create `Components.cs`: ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent; public record struct Burning(int Ticks) : IComponent; // a status that comes and goes public struct Dead : IComponent; // a tag: no fields ``` Components must be structs: a class fails the build with [EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006). Keep them small and split what systems read separately, because a pass loads only the columns it uses. ### Create a world and entities A `World` holds entities, their components, singletons and systems. Worlds share nothing; a server typically runs one per map or zone. Replace `Program.cs` with: ```csharp using EasyEcs; using var world = new World(); var units = new Entity[1_000]; world.CreateEntities(units, new Position(0, 0), new Velocity(1, 0), new Health(100)); for (int i = 0; i < units.Length; i += 10) units[i].SetBurning(40); // every tenth unit is on fire ``` `CreateEntities` places a whole wave in its final table at once; `world.CreateEntity(a, b, …)` creates one entity the same way. An `Entity` is a handle. Ids are recycled after `Destroy()`, and the handle's version makes sure an old handle never reaches the entity that reuses its id. More in [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components). ### Read and write components For every component the generator writes named members: `scout.Velocity` is a `ref` into storage, `SetBurning(…)` adds or overwrites, `HasBurning` and `RemoveBurning()` do what they say. Use these in your code; the generic API underneath (`Get()`, `Read()`, `Set(…)`, `Has()`, `Remove()`) is for generic code. Add to `Program.cs`: ```csharp Entity scout = units[1]; scout.Velocity = new Velocity(2, 0); // writes in place, through the ref float speed = scout.Velocity.X; // reads through the same ref: 2 scout.SetBurning(5); // adds the component bool burning = scout.HasBurning; // true scout.RemoveBurning(); // removes it: the entity keeps its row ``` Adding and removing a component are **structural changes**. They apply at once, anywhere, even in the middle of a system's pass. A `ref` stays valid until the next structural change and never across `await` ([`ref` and `await`](https://ecs.xgamedev.net/en/docs/guide/refs-and-await)). ### Query entities Outside systems (tools, tests, request handlers), ask the world directly. A `QueryFilter` adds conditions beyond the components: ```csharp var alive = QueryFilter.Create().Without(); // in real code: a static readonly field int movers = world.Count(alive); int onFire = world.Count(); Console.WriteLine($"{movers} movers, {onFire} on fire"); float front = 0; foreach (var item in world.Query(alive)) front = MathF.Max(front, item.Position.X); // items hand out refs; item.Entity is the handle ``` Queries allocate nothing. More in [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries), including struct jobs, the fastest ad-hoc pass. ### Write a system A system derives from `EcsSystem` and has one job. A `[ForEach]` method is its whole loop: it runs once per entity that has its component parameters, `ref` for what it writes and `in` for what it reads. Filters are attributes. Create `Systems.cs`: ```csharp using EasyEcs; public class MovementSystem : EcsSystem { [ForEach, Without] // movers that are not dead static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y); } public class BurnSystem : EcsSystem { [ForEach, Without] static void Burn(Entity unit, ref Burning burning, ref Health hp) { hp.Value -= 3; if (--burning.Ticks == 0) unit.RemoveBurning(); // safe in the middle of the pass } } ``` The generator compiles each method into a struct job that the JIT inlines into the row loop: no delegate, no virtual call per entity. The `ref` and `in` keywords also tell the scheduler what the system touches, which is how [parallel systems](https://ecs.xgamedev.net/en/docs/guide/threading) stay safe. More in [Systems](https://ecs.xgamedev.net/en/docs/guide/systems). ### Keep world state in a singleton Systems keep no state of their own ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007)). Data with one value per world, such as a clock or a score, is a **singleton**: a struct implementing `ISingletonComponent`. Add it to `Components.cs`: ```csharp public record struct Arena(long Tick, int Deaths) : ISingletonComponent; ``` A `[ForEach]` method takes a singleton as a parameter, resolved once per pass. Code outside a `[ForEach]` reaches it as `World.Arena` (generated) or `World.GetSingleton()`. Add to `Systems.cs`: ```csharp public class ClockSystem : EcsSystem { protected override void OnUpdate() => World.Arena.Tick++; } ``` More in [Singletons](https://ecs.xgamedev.net/en/docs/guide/singletons). ### React to state and order systems Systems never call each other ([EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008)); they cooperate through data. The death system writes a state, the `Dead` tag, and the corpse system reacts to it without the death system knowing it exists. `[UpdateAfter]` orders them by data flow. Add to `Systems.cs`: ```csharp [UpdateAfter] // after the damage is dealt public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp, ref Arena arena) { if (hp.Value > 0) return; unit.SetDead(); // a state change is data arena.Deaths++; } } [UpdateAfter] public class CorpseSystem : EcsSystem { protected override void OnUpdate() => World.DestroyEntities(); // every corpse in one pass } ``` The tag applies at once: the corpse system sees it in the same update, and `[Without]` keeps every other system away from the dead. Why this design scales is in [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles). ### Run the update loop Add the singleton and the systems, then call `world.Update()` on a fixed tick. Add to the end of `Program.cs`: ```csharp world.AddSingleton(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(50)); // 20 ticks per second for (int tick = 1; tick <= 100; tick++) { await timer.WaitForNextTickAsync(); world.Update(); // every system, synchronously } Console.WriteLine($"{world.Arena.Deaths} dead, the scout is at {scout.Position.X}"); ``` `Update()` runs every enabled system once, in registration order adjusted by `[UpdateBefore]` / `[UpdateAfter]`, and allocates nothing. A system can run less often by overriding `UpdateInterval`, or be switched off with `Enabled = false`. ### Add a second cadence with a system group Not everything runs every tick. A **system group** is a struct implementing `ISystemGroup`; systems marked `[UpdateInGroup]` run only when you call `world.Update()`. Add a report that prints once a second: ```csharp public struct Report : ISystemGroup; ``` ```csharp [UpdateInGroup] public class ReportSystem : EcsSystem { protected override void OnUpdate() => Console.WriteLine($"tick {World.Arena.Tick}: {World.EntityCount} units, " + $"{World.Count()} burning, {World.Arena.Deaths} dead"); } ``` Register it with the others (`world.AddSystem();`) and call its group every twentieth tick: ```csharp world.AddSystem(); for (int tick = 1; tick <= 100; tick++) { world.Update(); if (tick % 20 == 0) world.Update(); // once a second at 20 Hz } ``` On a real server, one group handles input whenever it arrives and another runs the simulation on its fixed tick. ## Run it ```bash dotnet run ``` With the [whole program](https://ecs.xgamedev.net/en/docs/getting-started#whole-program) below, it prints: ```text 1000 movers, 100 on fire tick 20: 1000 units, 100 burning, 0 dead tick 40: 900 units, 0 burning, 100 dead tick 60: 900 units, 0 burning, 100 dead tick 80: 900 units, 0 burning, 100 dead tick 100: 900 units, 0 burning, 100 dead the scout is at 200, the others at 100 ``` The hundred burning units lose 3 health per tick and die on the 34th tick; their corpses are destroyed in the same update. The scout moves twice as fast as the others. ## The whole program **Components.cs** ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent; public record struct Burning(int Ticks) : IComponent; // a status that comes and goes public struct Dead : IComponent; // a tag: no fields public record struct Arena(long Tick, int Deaths) : ISingletonComponent; public struct Report : ISystemGroup; ``` **Systems.cs** ```csharp using EasyEcs; public class MovementSystem : EcsSystem { [ForEach, Without] static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y); } public class BurnSystem : EcsSystem { [ForEach, Without] static void Burn(Entity unit, ref Burning burning, ref Health hp) { hp.Value -= 3; if (--burning.Ticks == 0) unit.RemoveBurning(); } } [UpdateAfter] public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp, ref Arena arena) { if (hp.Value > 0) return; unit.SetDead(); arena.Deaths++; } } [UpdateAfter] public class CorpseSystem : EcsSystem { protected override void OnUpdate() => World.DestroyEntities(); } public class ClockSystem : EcsSystem { protected override void OnUpdate() => World.Arena.Tick++; } [UpdateInGroup] public class ReportSystem : EcsSystem { protected override void OnUpdate() => Console.WriteLine($"tick {World.Arena.Tick}: {World.EntityCount} units, " + $"{World.Count()} burning, {World.Arena.Deaths} dead"); } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); var units = new Entity[1_000]; world.CreateEntities(units, new Position(0, 0), new Velocity(1, 0), new Health(100)); for (int i = 0; i < units.Length; i += 10) units[i].SetBurning(40); // every tenth unit is on fire Entity scout = units[1]; scout.Velocity = new Velocity(2, 0); float speed = scout.Velocity.X; scout.SetBurning(5); bool burning = scout.HasBurning; scout.RemoveBurning(); var alive = QueryFilter.Create().Without(); int movers = world.Count(alive); int onFire = world.Count(); Console.WriteLine($"{movers} movers, {onFire} on fire"); world.AddSingleton(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(50)); // 20 ticks per second for (int tick = 1; tick <= 100; tick++) { await timer.WaitForNextTickAsync(); world.Update(); // the default group: the simulation if (tick % 20 == 0) world.Update(); // once a second: the report } Console.WriteLine($"the scout is at {scout.Position.X}, the others at {units[2].Position.X}"); ``` ## Where to go next The simulation uses the core of EasyEcs. Each of these adds one capability to it: | To | Read | | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | Lay the program out as a real project: folders, one system per file, tests | [Structuring a real project](https://ecs.xgamedev.net/en/docs/guide/project-structure) | | Design features as data plus one-job systems | [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles) | | Send clients only what changed, or went away | [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking) | | Spawn kinds of units from a recipe | [Prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs) | | Find a player by name, the items of an owner | [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) | | Give each unit a list (a bag, a path) | [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) | | Use every core | [Threading](https://ecs.xgamedev.net/en/docs/guide/threading) | | Save the world and load it after a restart | [Saves](https://ecs.xgamedev.net/en/docs/guide/saves) | | Run the world in ASP.NET Core or a Worker Service | [Hosting in a .NET server](https://ecs.xgamedev.net/en/docs/guide/hosting) | | Test each system and the whole tick | [Testing systems](https://ecs.xgamedev.net/en/docs/guide/testing) | | See every API on one page | [Cheat sheet](https://ecs.xgamedev.net/en/docs/cheat-sheet) | - [Structuring a real project](https://ecs.xgamedev.net/en/docs/guide/project-structure): The same program as a project: folders, one system per file, the host, tests. - [Features](https://ecs.xgamedev.net/en/docs/features): Every feature, what it is for and what it costs. - [The battle server](https://ecs.xgamedev.net/en/docs/example): One server that uses every feature, also a benchmark and a test. - [Glossary](https://ecs.xgamedev.net/en/docs/glossary): The terms of these docs in a few sentences each. --- # Live demo > Thousands of entities moved by EasyEcs systems in your browser: .NET in WebAssembly, the C# source that runs beside it, live update times and FPS. URL: https://ecs.xgamedev.net/en/docs/demo Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/demo.md This page runs an EasyEcs world in your browser. Emitters drift along a curve and fire rings of sparks; drag slows the sparks down, so their color, set by speed, cools as they age; they flash where they hit a wall and fade out at the end of their life, and the emitters replace them. Move the pointer over the canvas and the sparks swirl towards it. Pick a count and watch what an update costs, and what the batch systems save over per-entity ones. > **Live demo**: open https://ecs.xgamedev.net/en/docs/demo in a browser to run it. > **Not a benchmark** > > Browsers do not run .NET's usual runtime, CoreCLR, yet: CoreCLR on WebAssembly is only a preview in .NET 11, and > an interpreter there. This page runs on .NET's Mono runtime, compiled ahead of time to WebAssembly (Mono AOT), > with WebAssembly's 128-bit SIMD, on one thread. That is slower than .NET on a server, so the update time here is > not a measurement of EasyEcs. The numbers measured with BenchmarkDotNet on a real machine are on the > [performance page](https://ecs.xgamedev.net/en/docs/performance). ## What runs here The world is `demo/EasyEcs.Demo` in the repository: a .NET 10 WebAssembly app that references EasyEcs.Core and its generator like any other project. Each animation frame, the page calls `Demo.Step(dt)` once: 1. The host writes the step into the `Clock` singleton and updates a motion group: `world.Update()` and `world.Update()` take turns, one per frame. Either one slows every spark by drag, then moves it. 2. `world.Update()` runs the default group in the order the systems were added: `LifetimeSystem` destroys the sparks whose time ran out, `OrbitSystem` moves the emitters along their curve, `BurstSystem` fires a ring from each emitter whose cooldown is over until the `Population` target is met again, `AttractSystem` pulls the sparks towards the `Pointer`, `BounceSystem` turns them back at the walls and gives them a `Flash`, and `FadeSystem` dims the flash and removes it. 3. `Frame.Write`, a `[ForEach]` method outside any system, copies each spark's position, heat (its speed) and light into one float array. 4. The page uploads that array to the GPU in one call, straight from the WebAssembly memory, and draws every spark as a soft point of light. The light fades a little each frame instead of being cleared, which draws the trails. ```mermaid flowchart LR P[Page] -->|"Step(dt)"| M["Update<Batched>() or
Update<PerEntity>()"] M --> U["world.Update()"] U --> F[Frame.Write] F -->|float array| P P -->|"Point(x, y)"| S[Pointer singleton] ``` No call crosses between JavaScript and .NET per entity, and nothing is allocated per frame on either side: the array lives on the pinned object heap, so its address never changes. The pointer is input, and input is data: the page writes it into the `Pointer` singleton, and `AttractSystem` reads it on the next update. ## Batch methods and SIMD Below the canvas, the page shows what the same motion costs written two ways, measured live. `DragSystem` and `MovementSystem` are plain `[ForEach]` methods, called once per spark. `DragBatchSystem` and `MovementBatchSystem` are [batch methods](https://ecs.xgamedev.net/en/docs/guide/systems#batch-methods): they receive spans over runs of whole rows, cast them to `Vector128` and work on two sparks per instruction, with one scalar step for an odd spark at the end. The cast is valid because `Position` and `Velocity` are two floats each, so a run of rows is one float array. Both pairs do the same work and give the same result. They sit in two system groups, `Batched` and `PerEntity`, and the host updates them in turns, one per frame, timing each: the picture does not change, both are measured on the same sparks, and the systems hold no mode flag. WebAssembly SIMD is 128 bits wide, so `Vector128` runs as hardware SIMD here while wider vectors do not; on a server the same code can use `Vector256` or `Vector`. The larger the count, the more the batch version saves. ## The code These are the files the demo is built from, included from the repository. Every system has one job and keeps no state: the clock, the walls, the pointer and the population target are singletons, and a wall hit is written as data (`Flash`) for `FadeSystem` to pick up ([ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles)). **Components** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Components: plain data on each entity, in pixels and seconds. public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; // Seconds left of a total: a spark fades in, fades out and is destroyed when it runs out. public record struct Lifetime(float Left, float Total) : IComponent; // Present while a spark glows after hitting a wall. It comes and goes: a presence bit, the row // stays. public record struct Flash(float Left) : IComponent; // A point that travels along a curve and fires bursts of sparks: Phase is where it is on the curve, // Cooldown the seconds until its next burst. public record struct Emitter(float Phase, float Cooldown) : IComponent; // Singletons: one value per world. // The walls, resized by the page with the canvas. public record struct Arena(float Width, float Height) : ISingletonComponent; // The step the page asked for and the number of steps so far, written by the host before each // update. public record struct Clock(float Dt, long Tick) : ISingletonComponent; // How many sparks the world keeps alive: the emitters replace the ones LifetimeSystem destroys. public record struct Population(int Target) : ISingletonComponent; // The visitor's pointer over the canvas, written by the page: input is data the systems read. public record struct Pointer(float X, float Y, bool Active) : ISingletonComponent; ``` **Groups** ```csharp using EasyEcs; namespace EasyEcs.Demo; // The two ways the demo moves its sparks. The host updates one group or the other before the // default group, taking turns, and times both: same work, same result, only the loop differs. // Batch methods over spans of whole tables, vectorized with SIMD. public struct Batched : ISystemGroup; // One call per spark: the plain [ForEach] method. public struct PerEntity : ISystemGroup; ``` **MovementBatchSystem** ```csharp using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using EasyEcs; namespace EasyEcs.Demo; // MovementSystem as a batch method: element i of both spans is the same spark, so the positions // and velocities of a run line up and add as vectors. [UpdateInGroup] public class MovementBatchSystem : EcsSystem { [ForEach] static void Move(Span positions, ReadOnlySpan velocities, in Clock clock) { // Position and Velocity are two floats each: one Vector128 is two sparks var p = MemoryMarshal.Cast>(positions); var v = MemoryMarshal.Cast>(velocities); var dt = Vector128.Create(clock.Dt); for (int i = 0; i < p.Length; i++) { p[i] += v[i] * dt; } // An odd run leaves one spark over if ((positions.Length & 1) != 0) { ref var last = ref positions[^1]; last.X += velocities[^1].X * clock.Dt; last.Y += velocities[^1].Y * clock.Dt; } } } ``` **DragBatchSystem** ```csharp using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using EasyEcs; namespace EasyEcs.Demo; // DragSystem as a batch method: the same slowdown over runs of whole rows at once. [UpdateInGroup] public class DragBatchSystem : EcsSystem { [ForEach] static void Slow(Span velocities, in Clock clock) { float keep = Units.Keep(clock.Dt); // WebAssembly SIMD is 128 bits wide: one Vector128 holds the X and Y of two sparks. // The cast is valid because Velocity is exactly two floats, so a run of rows is one float // array var v = MemoryMarshal.Cast>(velocities); for (int i = 0; i < v.Length; i++) { v[i] *= keep; } // An odd run leaves one spark over if ((velocities.Length & 1) != 0) { ref var last = ref velocities[^1]; last.X *= keep; last.Y *= keep; } } } ``` **MovementSystem** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Moves every spark by its velocity over the step. One call per spark. [UpdateInGroup] public class MovementSystem : EcsSystem { [ForEach] static void Move(ref Position p, in Velocity v, in Clock clock) { p.X += v.X * clock.Dt; p.Y += v.Y * clock.Dt; } } ``` **DragSystem** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Slows every spark down, as air would: a burst expands fast and settles. One call per spark. [UpdateInGroup] public class DragSystem : EcsSystem { [ForEach] static void Slow(ref Velocity v, in Clock clock) { float keep = Units.Keep(clock.Dt); v.X *= keep; v.Y *= keep; } } ``` **LifetimeSystem** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Ages every spark and destroys the ones whose time ran out. public class LifetimeSystem : EcsSystem { [ForEach] static void Age(Entity spark, ref Lifetime life, in Clock clock) { life.Left -= clock.Dt; if (life.Left <= 0) { spark.Destroy(); } } } ``` **OrbitSystem** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Moves the emitters along a slow Lissajous curve through the arena. public class OrbitSystem : EcsSystem { // Radians of the curve per second. private const float Speed = 0.11f; [ForEach] static void Orbit(ref Position p, ref Emitter emitter, in Arena arena, in Clock clock) { emitter.Phase += Speed * clock.Dt; float t = emitter.Phase; p.X = arena.Width * (0.5f + 0.36f * MathF.Sin(3 * t)); p.Y = arena.Height * (0.5f + 0.34f * MathF.Sin(2 * t + MathF.PI / 2)); } } ``` **BurstSystem** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Keeps the population at its target: each emitter whose cooldown is over fires the sparks missing // as one ring from where it stands. public class BurstSystem : EcsSystem { // Seconds between two bursts of an emitter, at least and at most. private const float MinInterval = 0.25f; private const float MaxInterval = 0.6f; // Seconds a spark lives, at least and at most: mixed lifetimes keep the bursts from falling in // step. private const float MinLife = 1.6f; private const float MaxLife = 4f; [ForEach] static void Burst(ref Emitter emitter, in Position at, in Arena arena, in Clock clock, in Population population, World world) { emitter.Cooldown -= clock.Dt; if (emitter.Cooldown > 0) { return; } long tick = clock.Tick; int seed = (int)(emitter.Phase * 1000); emitter.Cooldown = MinInterval + Units.Unit(tick, seed) * (MaxInterval - MinInterval); // A burst takes at most a sixteenth of the target, so an empty world fills over a second // or so and the lifetimes of the first sparks are spread out int missing = Math.Min(population.Target - world.Count(), population.Target / 16); float speed = Units.BurstSpeed * MathF.Min(arena.Width, arena.Height); for (int i = 0; i < missing; i++) { int n = seed + i * 3; float angle = Units.Unit(tick, n) * MathF.Tau; // Most sparks leave at nearly the same speed: the burst reads as a ring float v = speed * (0.75f + 0.25f * Units.Unit(tick, n + 1)); float life = MinLife + Units.Unit(tick, n + 2) * (MaxLife - MinLife); var spark = world.Instantiate(Units.Spark); spark.Position = at; spark.Velocity = new Velocity(MathF.Cos(angle) * v, MathF.Sin(angle) * v); spark.Lifetime = new Lifetime(life, life); } } } ``` **AttractSystem** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Pulls the sparks towards the pointer while it is over the canvas, and swirls them around it. public class AttractSystem : EcsSystem { // Pull and swirl, in pixels per second squared at the softening distance. private const float Pull = 1800f; private const float Swirl = 1400f; // Pixels within which the force stops growing, so sparks pass through the pointer smoothly. private const float Soft = 40f; [ForEach] static void Attract(ref Velocity v, in Position p, in Pointer pointer, in Clock clock) { if (!pointer.Active) { return; } float dx = pointer.X - p.X; float dy = pointer.Y - p.Y; // Falls off with distance (1 / r): near sparks orbit, far ones drift in float scale = clock.Dt * Soft / (dx * dx + dy * dy + Soft * Soft); v.X += (dx * Pull - dy * Swirl) * scale; v.Y += (dy * Pull + dx * Swirl) * scale; } } ``` **BounceSystem** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Turns sparks back at the walls and makes them flash: the hit is written as data (Flash), // FadeSystem takes it from there. public class BounceSystem : EcsSystem { [ForEach] static void Bounce(Entity spark, ref Position p, ref Velocity v, in Arena arena) { bool hit = false; if (p.X < 0 || p.X > arena.Width) { p.X = Math.Clamp(p.X, 0, arena.Width); v.X = -v.X; hit = true; } if (p.Y < 0 || p.Y > arena.Height) { p.Y = Math.Clamp(p.Y, 0, arena.Height); v.Y = -v.Y; hit = true; } if (hit) { spark.SetFlash(Units.FlashTime); } } } ``` **FadeSystem** ```csharp using EasyEcs; namespace EasyEcs.Demo; // Dims the flash of the sparks that hit a wall and removes it when it is gone. public class FadeSystem : EcsSystem { [ForEach] static void Fade(Entity spark, ref Flash flash, in Clock clock) { flash.Left -= clock.Dt; if (flash.Left <= 0) { // Flips a presence bit: the spark keeps its row spark.RemoveFlash(); } } } ``` **Units** ```csharp using EasyEcs; namespace EasyEcs.Demo; // The recipes and tuning of the demo, shared by the systems. public static class Units { // The recipe of a spark: a row outside the world that Instantiate copies. A burst fills in the // values. public static readonly Prefab Spark = new Prefab().Set(new Position(), new Velocity(), new Lifetime(1, 1)); // Seconds a spark glows after a wall hit. public const float FlashTime = 0.35f; // The speed of a fresh spark, as a fraction of the arena's shorter side per second. Drag slows // it down, so the color of a spark (by speed) tells how old it is. public const float BurstSpeed = 0.6f; // The share of its speed a spark loses per second, to drag. public const float Drag = 0.8f; // What a spark keeps of its speed over a step of `dt` seconds. public static float Keep(float dt) => MathF.Max(0, 1 - Drag * dt); // The emitters, spread evenly along their curve. public const int Emitters = 5; // A deterministic random number per (tick, n): the same run every time, no generator object to // keep. public static uint Roll(long tick, int n) { ulong x = (ulong)tick * 0x9E3779B97F4A7C15UL ^ (uint)n * 0xBF58476D1CE4E5B9UL; x ^= x >> 31; x *= 0x94D049BB133111EBUL; return (uint)(x ^ (x >> 29)); } // A roll as a float in [0, 1). public static float Unit(long tick, int n) => (Roll(tick, n) >> 8) * (1f / (1 << 24)); } ``` **Frame** ```csharp using EasyEcs; namespace EasyEcs.Demo; // What the page draws, written between updates into one float array the page reads in place: // x, y, heat (0..1: the color) and light (0..2: the brightness) per spark. public static class Frame { public const int Stride = 4; // Seconds a spark takes to fade in at its birth and out before its end. private const float FadeTime = 0.6f; // A [ForEach] method outside a system: the generator writes // Frame.Write(world, frame, ref count) for the host. [ForEach] static void Write(in Position p, in Velocity v, in Lifetime life, Maybe flash, in Arena arena, float[] frame, ref int count) { // Heat is the speed against a fresh spark's: drag cools a spark from hot to cold float full = Units.BurstSpeed * MathF.Min(arena.Width, arena.Height); float heat = MathF.Min(1, MathF.Sqrt(v.X * v.X + v.Y * v.Y) / full); float fade = Math.Clamp(MathF.Min(life.Total - life.Left, life.Left) / FadeTime, 0, 1); // A wall hit flashes to the hot end and doubles the light, then fades with the Flash float hit = flash.HasValue ? flash.Value.Left / Units.FlashTime : 0; int i = count++ * Stride; frame[i] = p.X; frame[i + 1] = p.Y; frame[i + 2] = MathF.Max(heat, hit); frame[i + 3] = fade * (1 + hit); } } ``` **Host** ```csharp using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.JavaScript; using System.Runtime.Intrinsics; using System.Runtime.Versioning; using EasyEcs; namespace EasyEcs.Demo; // The host: owns the world on the page's thread and answers the page. Every call is a few numbers; // the sparks reach the page through the frame array, which lives on the pinned object heap so its // address never changes. [SupportedOSPlatform("browser")] public static partial class Demo { private static World? _world; private static float[] _frame = []; private static double _updateMs; // The last motion time of each group: [0] per entity, [1] batched. private static readonly double[] _motionMs = new double[2]; // A new world of `count` sparks in an arena of `width` x `height` pixels. [JSExport] public static void Reset(int count, float width, float height) { _world?.Dispose(); _world = new World(new WorldOptions { InitialEntityCapacity = count + Units.Emitters }); _world.SetArena(width, height); _world.SetClock(0, 0); _world.SetPopulation(count); _world.SetPointer(0, 0, false); // Motion, in either group: Update() or Update() runs it _world.AddSystem(); _world.AddSystem(); _world.AddSystem(); _world.AddSystem(); // The default group, run by Update() after the motion, in this order _world.AddSystem(); _world.AddSystem(); _world.AddSystem(); _world.AddSystem(); _world.AddSystem(); _world.AddSystem(); // The emitters, evenly spread along their curve; the first update moves them onto it for (int i = 0; i < Units.Emitters; i++) { float phase = i * MathF.Tau / Units.Emitters; _world.CreateEntity(new Position(), new Emitter(phase, i * 0.1f)); } // The population never exceeds its target: the array holds every spark of any frame if (_frame.Length < count * Frame.Stride) { _frame = GC.AllocateUninitializedArray(count * Frame.Stride, pinned: true); } } // The canvas changed size: sparks outside the new walls bounce back in on the next update. [JSExport] public static void Resize(float width, float height) => World.SetArena(width, height); // The pointer moved over the canvas (active) or left it. [JSExport] public static void Point(float x, float y, bool active) => World.SetPointer(x, y, active); // Milliseconds the last update of the batch (true) or per-entity (false) motion group took. [JSExport] public static double MotionMs(bool batched) => _motionMs[batched ? 1 : 0]; // Which vector widths run as hardware SIMD here, as bits: 1 = Vector128, 2 = Vector256, // 4 = Vector512, 8 = Vector. [JSExport] public static int Simd() => (Vector128.IsHardwareAccelerated ? 1 : 0) | (Vector256.IsHardwareAccelerated ? 2 : 0) | (Vector512.IsHardwareAccelerated ? 4 : 0) | (Vector.IsHardwareAccelerated ? 8 : 0); // Advances the world by `dt` seconds, then writes the frame. Returns the number of sparks in // it. [JSExport] public static int Step(float dt) { var world = World; ref var clock = ref world.Clock; clock.Dt = dt; clock.Tick++; // The two motion groups take turns, one per step. They do the same work, so the picture // does not change, and each is timed on the same sparks bool batched = (clock.Tick & 1) == 0; long start = Stopwatch.GetTimestamp(); if (batched) { world.Update(); } else { world.Update(); } long moved = Stopwatch.GetTimestamp(); world.Update(); long end = Stopwatch.GetTimestamp(); _motionMs[batched ? 1 : 0] = Stopwatch.GetElapsedTime(start, moved).TotalMilliseconds; _updateMs = Stopwatch.GetElapsedTime(start, end).TotalMilliseconds; int count = 0; Frame.Write(world, _frame, ref count); return count; } // Where the frame array starts in the WebAssembly memory, for a Float32Array over it. [JSExport] public static unsafe int FrameAddress() => (int)Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(_frame)); // Milliseconds the last update took (the motion group and the default group). [JSExport] public static double UpdateMs() => _updateMs; // Live entities (the sparks and the emitters), after the last update. [JSExport] public static int EntityCount() => World.EntityCount; private static World World => _world ?? throw new InvalidOperationException("Call Reset first."); } ``` ## Why is it slower than the benchmarks? Three things a server has and this page does not: - **CoreCLR and RyuJIT.** The browser runs Mono, compiled ahead of time to WebAssembly, which the browser compiles again to machine code. That code is good, but not as tight as what RyuJIT makes for the machine it runs on, and vectors stop at 128 bits. - **Threads.** The page runs on the browser's main thread. `ParallelSystems` and `[ForEach(Parallel = true)]` need more than one, so the demo leaves them off. - **A quiet machine.** The page shares its thread with drawing, the browser and every other tab, so the update time moves from frame to frame. The data layout, the generated jobs and the zero allocations are the same in both: what you see here is the shape of the work, and the [performance page](https://ecs.xgamedev.net/en/docs/performance) is its speed. ## Run it yourself The page loads the runtime from `docs/public/demo/_framework`, published from `demo/EasyEcs.Demo` by `docs/scripts/build-demo.sh` (`bun run demo:build` in `docs/`), which installs the `wasm-tools` workload that Mono AOT needs when it is missing. Change a system, run the script, and `bun run dev` serves the page with your code. The same systems run unchanged in a console app or a server: only `Demo.cs`, the host, knows about the browser. ## Related - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): Install EasyEcs and write a world like this one step by step. - [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles): Why each system here has one job and talks to the others only through data. - [Example: a battle server](https://ecs.xgamedev.net/en/docs/example): A larger world that uses every feature. - [Performance](https://ecs.xgamedev.net/en/docs/performance): The numbers measured with BenchmarkDotNet on a real machine. --- # ECS principles > How to design features with an ECS: eight rules for entities, components, singletons and systems, the analyzer checks behind them, and a checklist. URL: https://ecs.xgamedev.net/en/docs/ecs-principles Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/ecs-principles.md EasyEcs separates **data** (entities, components, singletons) from **behaviour** (systems). That split is what makes iteration fast, with dense columns and no virtual call per entity, and it is also what keeps a large code base decoupled: systems never know about each other, only about data. This page gives each role, eight rules for designing with them and a checklist for a new feature. The analyzer enforces the mechanical parts at build time. ## Who does what ```mermaid flowchart LR subgraph Data E[Entity
identity] C[Component
per-entity data] S[Singleton
per-world data] end subgraph Behaviour A[System A] B[System B] H[System C] end A -->|reads / writes| C A -->|reads / writes| S B -->|reads / writes| C H -->|reads| C H -->|reads / writes| S E -.->|has| C ``` There are no arrows between systems. Every dependency goes through data, and every piece of behaviour runs inside the schedule, in registration order or in the order `[UpdateBefore]` / `[UpdateAfter]` declare. | Element | Is | Is not | | ------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | **Entity** | An identity (index and version), held as an `Entity` handle in code and as an `EntityId` in data | A container of logic, a base class, a place for fields | | **Component** | A struct of fields for one aspect of one entity (`Health`, `Velocity`); computed getters are fine | A class, an object with behaviour, a holder of references to systems or services | | **Tag** | An empty component (`Dead`, `Frozen`) used as a filter | A boolean flipped every tick (use a field) | | **Singleton** | One struct per world: clock, configuration, counters, a spatial grid | A static field (it would be shared by every world) | | **System** | Behaviour with one responsibility, reading and writing components and singletons | A place to keep state, or a service other systems call | ## The rules The examples share these components: ```csharp public record struct Health(int Value) : IComponent; public record struct Burning(int Ticks, int DamagePerTick) : IComponent; // a status effect public struct Dead : IComponent; // a tag ``` ### 1. One system, one responsibility Name a system after the one thing it does. If its description needs "and", split it. ```csharp // Before: burning AND death in one system. Death is noticed only for burning units: // a unit killed by anything else is never marked Dead. public class StatusSystem : EcsSystem { [ForEach, Without] static void Tick(Entity unit, ref Burning burning, ref Health hp) { hp.Value -= burning.DamagePerTick; if (--burning.Ticks == 0) unit.RemoveBurning(); if (hp.Value <= 0) unit.SetDead(); } } ``` ```csharp // After: each concern can be removed, reordered or tested alone, and death covers every damage source. public class BurnSystem : EcsSystem { [ForEach, Without] static void Burn(Entity unit, ref Burning burning, ref Health hp) { hp.Value -= burning.DamagePerTick; if (--burning.Ticks == 0) unit.RemoveBurning(); } } [UpdateAfter] // after the systems that deal damage public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp) // `in`: it only reads Health { if (hp.Value <= 0) unit.SetDead(); } } ``` Splitting costs nothing at run time. Every `[ForEach]` method is its own inlined struct job either way, and the per-system cost of an update is three virtual calls (`UpdateInterval`, `OnUpdate` and the generated code) plus one query-cache lookup per `[ForEach]` method and one lookup per singleton parameter. When in doubt, split. ### 2. Systems are stateless State inside a system is invisible to queries, to other systems, to tests and to saves, and it disappears or doubles when the system is removed or added twice. Put it in data: | State | Where | | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | | Per entity (cooldown, target, path) | A component | | Per world (tick, score, configuration, spatial grid) | A singleton | | Lookups by value (a player by name, the items of an owner) | An indexed component ([indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations)), not a dictionary kept in sync by hand | | Derived and rebuildable (a scratch list reused every update) | A `readonly` field on the system is fine | ```csharp // Before (EECS007): the count lives in the system, where no query, test or other system can see it. public class DeathSystem : EcsSystem { public int Deaths; [ForEach, Without] void Die(Entity unit, in Health hp) { if (hp.Value > 0) return; unit.SetDead(); Deaths++; } } ``` ```csharp // After: the count is world state; anyone can read it (world.Score.Deaths). public record struct Score(int Deaths) : ISingletonComponent; [UpdateAfter] public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp, ref Score score) // a singleton parameter { if (hp.Value > 0) return; unit.SetDead(); score.Deaths++; } } ``` `readonly` fields for dependencies or reusable scratch buffers, `init`-only properties and computed properties are allowed ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007)). ### 3. Systems never reference systems A system that holds another system ([EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008)), or reaches one through `World.GetSystem()`, can no longer be removed, reordered or tested alone. Cooperate through data instead: - **Pipeline:** an earlier system writes a component, a later one reads it. Register the writer first, or order them with `[UpdateAfter]`. - **Reacting to a state:** a system queries the state another one wrote; the writer does not change when a reader is added ([rule 4](https://ecs.xgamedev.net/en/docs/ecs-principles#4-state-changes-are-data)). ```csharp // Reacts to Dead; DeathSystem does not know it exists. [UpdateAfter] public sealed class CorpseSystem : EcsSystem { protected override void OnUpdate() => World.DestroyEntities(); // every corpse in one pass } ``` ```mermaid flowchart LR I[InputSystem] -->|writes Velocity| M[MovementSystem] M -->|writes Position| G[AoiSystem] D[DeathSystem] -->|sets Dead| R[RespawnSystem] D -->|sets Dead| C[CorpseSystem] ``` `GetSystem()` is for tooling, tests and the code that hosts the world. ### 4. State changes are data When something happens to an entity, write its new state: set a tag (`Dead`) or a field. The systems that care query that state later in the update, in the order of the schedule: movement and combat skip `Dead` entities, `CorpseSystem` removes them, a `RespawnSystem` could revive players. None of them is known to `DeathSystem`, and adding one changes no existing system. The same holds for what an entity leaves behind. A resource outside the world (a socket, a reserved seat) is a [cleanup component](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable): destroying the entity keeps it, tagged `Destroyed`, until a system releases the resource. There is no destroy event to subscribe to. ### 5. Choose the cheapest representation for frequent changes Removing a component, or adding back one the entity had before, flips a presence bit: the entity keeps its row. Gaining a component its table has no column for copies the entity's row into another table, once. Tags for states that come and go (`Stunned`, `Burning`, `Dead`) are therefore cheap. For values that change every tick, a field is still cheaper than a structural change: - a countdown field (`Burning.Ticks`) instead of re-adding a component every tick; - change detection by change ticks: mark the component `ITrackChanges` and give the consumer `[Changed]`, instead of adding and removing a `Changed` tag or scanning every row ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking)). A write is any `ref` access, so compare values when a write may leave the value as it was; - removal detection the same way: `[Removed]` visits the entities that lost a tracked `T`, instead of a `Lost` tag added next to every removal ([removal detection](https://ecs.xgamedev.net/en/docs/guide/change-tracking#removal-detection)); - pausing with `Disable()`, which hides a component and keeps its value, instead of removing it and storing the value elsewhere ([cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable)); - kinds of entities as [prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs): data that belongs to no world, instantiated where needed, instead of template entities that every query must exclude. ```csharp public record struct Facing(float Angle) : IComponent, ITrackChanges; // tracked: rows record their last write public record struct NetSync(Facing Sent) : IComponent; // what clients last heard public record struct Outbox(int Updates) : ISingletonComponent; public class SyncSystem : EcsSystem { [ForEach, Changed] // only entities whose Facing was written since this system last ran static void Sync(in Facing facing, ref NetSync sync, ref Outbox outbox) { if (facing == sync.Sent) return; // written but unchanged: nothing to send sync = new NetSync(facing); outbox.Updates++; // a real server queues the update here } } ``` ### 6. Let the schedule order effects Changes are immediate: a component a system adds is visible to every later system of the same update, and to the rest of the same pass. Within one pass each entity is visited at most once, and entities that join a matching table during the pass (created, or moved into a matching table) wait for the next pass. So the order of effects is the order of systems, never the order in which a system happens to visit entities: ```csharp [UpdateAfter] // after the damage; respawn and loot are ordered after it public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp, ref Score score) { if (hp.Value > 0) return; unit.SetDead(); // systems after DeathSystem see Dead in this update score.Deaths++; } } ``` The full rules are in [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes). ### 7. Keep entity handles, never refs, across boundaries A `ref` from `Get()` or a `Query` item is valid until the next structural change (of any entity); the `ref` parameters of a `[ForEach]` method stay valid through their own body's changes. None is valid across `await`. Keep `Entity` handles, which are checked on every access, and read components again when you need them ([`ref` and `await`](https://ecs.xgamedev.net/en/docs/guide/refs-and-await)). Inside data, keep the `EntityId` instead of the handle: an `Entity` field makes a component managed ([EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017)), and `world.TryGetEntity(id, out var entity)` turns the id back into a handle and tells you whether the entity still lives. ### 8. Choose how to hold a collection A component may hold a `List`, a `Dictionary` or an array, but its row stores only the reference. The world sees a write when code takes the component by `ref`, not when the collection behind it changes. So: - **Change it only through `ref`** (a `ref` parameter, `Get`, `TryGetRef`): the row is stamped for `[Changed]`, and parallel systems schedule the write. Changing it through an `in` parameter is a race that goes unnoticed; the analyzer reports it ([EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011)). - **Snapshots share it**: `Capture` copies the reference, not the collection, so restoring brings back the list as it is now. Snapshots are for plain data; saves serialize the collection anyway. A `DynamicBuffer` has neither problem: its writes need a `ref`, and snapshots copy its elements. Then pick the representation by what the items are: | Items | Hold them as | Why | | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | Things with their own state, queried or changed on their own (inventory items, guild members, buffs) | **One entity per item** with a link to its owner ([indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations)) | Each item has its own components, change ticks, queries and parallel schedule, copied by value in snapshots | | A list that belongs to one entity, sent or saved when it changes (a bag of loot, a path, recent hits) | **A [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers)** component | Every write needs a `ref`, so each change is tracked; snapshots copy the elements; a write through `in` does not compile | | A small, bounded set of values (cooldown slots, the last few inputs) | **A fixed `[InlineArray]` array** in an unmanaged component | No GC, copied by value everywhere, every change a `ref` write | | Data read and written as a whole, usually with the save (quest progress, settings, unlocked achievements) | **A collection in a component**, changed through `ref` | One row per player instead of thousands of entities; loaded and saved with the player | | Read-mostly data replaced as a whole (a patrol route) | **An immutable collection** (`ImmutableArray`) | Assigning a new one through `ref` is a tracked write; a snapshot keeps the old one | ```csharp [System.Runtime.CompilerServices.InlineArray(4)] public struct Slots4 { private int _first; } // 4 ints stored inline public struct Cooldowns : IComponent, ITrackChanges { public Slots4 ReadyAt; } // unmanaged: nothing to share public struct Quests : IComponent, ITrackChanges // saved and loaded with the player { public Dictionary Progress; } public record struct ItemOf(EntityId Owner) : IComponent, IIndexed // an inventory: items point at players { public EntityId Key => Owner; } public static class PlayerRules { // The tick a slot is ready again, not a countdown: no system writes every row every tick, so only uses are changes public static bool TryUse(Entity player, int slot, int tick, int cooldown) { if (player.Cooldowns.ReadyAt[slot] > tick) return false; // a read: no stamp player.WriteCooldowns().ReadyAt[slot] = tick + cooldown; // a write: the row is stamped return true; } public static void Advance(Entity player, int quest) { var progress = player.WriteQuests().Progress; // a write: the row is stamped progress[quest] = progress.TryGetValue(quest, out int step) ? step + 1 : 1; } public static void Give(World world, Entity player, int item) => world.CreateEntity(new ItemOf(player), new Health(item)); // a new row: tracked, indexed, snapshotted public static int Carried(World world, Entity player) => world.ItemOfIndex.Count(player); } ``` ## How the rules are enforced The analyzer turns the mechanical parts of these rules into build errors, so a code review does not have to catch them: | Rule | Broken by | Caught by | | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ---------------------------------------------------------------------------- | | Components are data | A class implementing `IComponent` | [EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006) | | [2. Systems are stateless](https://ecs.xgamedev.net/en/docs/ecs-principles#2-systems-are-stateless) | A mutable field, settable property or event on a system | [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007) | | [3. Systems never reference systems](https://ecs.xgamedev.net/en/docs/ecs-principles#3-systems-never-reference-systems) | A system-typed member, `GetSystem()` inside a system | [EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008) | | [6. Let the schedule order effects](https://ecs.xgamedev.net/en/docs/ecs-principles#6-let-the-schedule-order-effects) | `[UpdateBefore]` / `[UpdateAfter]` in a cycle | [EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019) | | [7. Keep handles, not refs](https://ecs.xgamedev.net/en/docs/ecs-principles#7-keep-entity-handles-never-refs-across-boundaries) | An `Entity` field in a component | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) (warning) | | [8. Choose how to hold a collection](https://ecs.xgamedev.net/en/docs/ecs-principles#8-choose-how-to-hold-a-collection) | Changing a collection through `in` | [EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) | The full list, with a fix for each rule, is in [Analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer). ## Checklist for a new feature 1. List the data: which components (per entity) and singletons (per world) does it need? 2. List the behaviours, one system each, named by what it does. 3. Order the systems by data flow (registration order, `[UpdateBefore]` / `[UpdateAfter]`): producers before consumers. 4. Express reactions across modules as systems querying the state another system wrote, never as calls between systems. 5. Pick how each collection is held ([rule 8](https://ecs.xgamedev.net/en/docs/ecs-principles#8-choose-how-to-hold-a-collection)). 6. Build: the analyzer rejects what breaks these rules. 7. Test each system alone: create a world, add the system and the data it reads, call `Update()`, assert on data. ## Related - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): The rules applied, step by step, in a small simulation. - [Systems](https://ecs.xgamedev.net/en/docs/guide/systems): Parameters, filters, ordering and groups of `[ForEach]` methods. - [Analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer): Every EECS rule, why it exists and how to fix it. --- # Cheat sheet > The everyday EasyEcs API on one page: entities, generated members, queries, [ForEach] parameters, attributes, singletons, indexes, prefabs, saves, options. URL: https://ecs.xgamedev.net/en/docs/cheat-sheet Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/cheat-sheet.md The whole everyday API of EasyEcs on one page, as tables and short code. Each section links to the guide page that explains it. Everything is in one namespace: `using EasyEcs;`. The examples on this page share these declarations: ```csharp public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent, ITrackChanges; // tracked: writes are recorded public record struct Team(int Id) : IComponent, IIndexed { public int Key => Id; } public record struct Zone(int Id) : IComponent, IGroup { public int Group => Id; } public record struct OwnedBy(EntityId Owner) : IComponent, IIndexed { public EntityId Key => Owner; } public record struct MemberOf(EntityId Target) : IRelation; // many links per entity public record struct Loot(int Item); // a DynamicBuffer element public record struct Seat(int Number) : ICleanupComponent; // released after destroy public struct Dead : IComponent; // a tag public record struct Clock(long Tick) : ISingletonComponent; // one per world ``` ## Declare data | Declare | Means | Guide | | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | `struct X : IComponent` | Per-entity data, one column per type | [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components) | | `struct X : IComponent` with no fields | A tag: a yes-or-no state used in filters | [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components) | | `struct X : ISingletonComponent` | One value per world | [Singletons](https://ecs.xgamedev.net/en/docs/guide/singletons) | | `: ITrackChanges` | Rows record the tick of their last write and removal | [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking) | | `: IIndexed` with `Key` | Found by value through `world.Index()` | [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) | | `: IIndexed` | A link to one entity, found from the target | [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) | | `: IRelation` with `Target` | Many links per entity, kept in a buffer | [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) | | `: IGroup` with `Group` | Splits tables by value after `world.GroupBy()` | [Groups](https://ecs.xgamedev.net/en/docs/guide/groups) | | `: ICleanupComponent` | Outlives `Destroy`: the other components go, the entity gets the `Destroyed` tag and stays until a system removes the last cleanup component | [Cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) | | `Disabled` | The tag an entity carries while its `T` is disabled: query it to find the paused ones | [Cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) | | `DynamicBuffer` | A list per entity, every write tracked | [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) | | `ChildOf(EntityId Parent)` | The built-in hierarchy link | [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy) | | `struct G : ISystemGroup` | A group of systems with its own cadence | [Systems](https://ecs.xgamedev.net/en/docs/guide/systems) | | `: IGroupWith` / `IGroupWithout` on a group (or an interface it implements) | The group's systems visit only entities with / without `T`; a generic interface gives each actor type its own filtered group | [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#group-filters) | | `class S : EcsSystem` | A generic system: each closed type (`S`) is a system of its own | [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#generic-systems) | Components are structs ([EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006)). Keep an entity link as an `EntityId`, not an `Entity` ([EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017)). ## World | Call | Does | | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------- | | `new World(options)` | An isolated world; `Dispose()` runs every `OnDestroy` | | `world.Update()` | Runs the default group's systems once | | `world.Update()` | Runs one system group | | `world.AddSystem()` / `AddSystem(instance)` | Adds a system (runs `OnCreate`) | | `world.RemoveSystem()` / `GetSystem()` / `Systems` | Removes, finds, lists systems | | `world.EntityCount` / `Entities` | Live entities and an allocation-free walk over them | | `world.ChangeTick` | The current change tick | | `world.UpdateCount` | Completed `Update()` calls of the default group | | `world.EnsureCapacity(n)` / `EnsureCapacity(prefab, n)` / `EnsureEntityCapacity(n)` | Pre-size before a known peak or a wave | | `world.TryGetEntity(id, out e)` / `GetEntity(id)` / `IsAlive(id)` | From an `EntityId` back to a checked handle | | `world.Describe()` | Tables, columns, rows and bytes, for tools | ## Entities ```csharp using var world = new World(); Entity unit = world.CreateEntity(new Position(0, 0), new Velocity(1, 0), new Health(100)); ``` The generic calls, what the [generated members](https://ecs.xgamedev.net/en/docs/cheat-sheet#generated-members) call; code that names a component uses the members (`unit.Velocity`, `SetHealth(50)`, `RemoveDead()`), as in the example under the table. | Call | Does | Structural | | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------- | | `world.CreateEntity(a, b, …)` | Creates with up to 9 components, straight into the final table | yes | | `entity.Set(a, b, …)` | Adds or overwrites up to 9 components in one move; returns the entity | yes | | `entity.Remove()` | Removes components it has; returns the entity | yes | | `entity.GetOrAdd()` | `ref T`, added with the default value if missing | when added | | `entity.Get()` | `ref T` for writing (a write for change tracking) | no | | `entity.Read()` | `ref readonly T` (never a write) | no | | `entity.TryGet(out T copy)` | A copy, if present | no | | `entity.TryGetRef(out bool found)` | `ref T` or a null ref | no | | `entity.Has()` / `Has()` | Presence of one or all | no | | `entity.Disable()` / `Enable()` / `IsDisabled()` | Hides a component, keeping its value | yes | | `entity.Clone()` | A copy of the entity in its world | yes | | `entity.Run(ref job)` / `Run(ref job, filter)` | Runs an `IForEachEntity` job on this entity with the refs a pass gives; `false` when it is not alive, lacks a component or fails the filter | when the job makes one | | `entity.Destroy()` | Destroys it; its id is recycled with a new version | yes | | `entity.IsAlive` / `Id` / `World` | Handle state; every access checks the version | no | | `entity.Describe()` | Its component values, for debuggers and logs | no | | `EntityId` / `EntityId.Null` / `id.IsNull` / `id.Index` / `id.Version` | The 8-byte id to keep in components; `Null` is the default value | no | ```csharp unit.Velocity.X = 2; // write in place through the ref float x = unit.Position.X; // a read (ref readonly for a tracked component) unit.Set(new Health(50), new Dead()); // both in one call: shorter, same cost unit.RemoveDead(); // flips a presence bit: the row stays if (unit.TryGetHealth(out var hp)) { /* hp is a copy */ } ``` ```csharp public struct TakeHit : IForEachEntity { public int Damage; public static int Writes => 1; // bit 0: Health counts as written public void Execute(Entity target, ref Health hp) => hp.Value -= Damage; } ``` ```csharp var hit = new TakeHit { Damage = 30 }; bool applied = unit.Run(ref hit); // a request handled on its entity ``` A `ref` stays valid until the next structural change and never across `await` ([`ref` and `await`](https://ecs.xgamedev.net/en/docs/guide/refs-and-await)). ## Generated members The source generator gives every component, tag and singleton named members (C# 14 extension members). Each one is an inlined call to the generic API above. | Declared | Generated | | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Component `Position` | `e.Position` (`ref`), `HasPosition`, `TryGetPosition(out p)`, `GetOrAddPosition()`, `SetPosition(x, y)`, `RemovePosition()`, `DisablePosition()`, `EnablePosition()`, `IsPositionDisabled` | | Tracked or indexed `Health` | `e.Health` is `ref readonly`; write with `SetHealth(…)` or `WriteHealth()` (`ref`, tracked only) | | Tag `Dead` | `e.IsDead`, `SetDead()`, `RemoveDead()` | | Indexed `Team` | `world.TeamIndex` (`world.Index()`) | | Grouped `Zone` | `filter.InZone(id)` (`InGroup(id)`) | | Buffer element `Loot` | `e.Loot` (`ref readonly DynamicBuffer`), `HasLoot`, `WriteLoot()`, `GetOrAddLoot()`, `RemoveLoot()` | | Relation `MemberOf` | `e.AddMemberOf(target)`, `RemoveMemberOf(target)`, `LinksMemberOf(target)`, `world.MemberOfIndex` | | Singleton `Clock` | `world.Clock` (`ref`), `HasClock`, `GetOrAddClock()`, `SetClock(…)`, `RemoveClock()` | | On a `Prefab` | `SetPosition(…)`, `RemovePosition()` return the prefab; `prefab.Position` (read-only), `HasPosition`, `IsDead` | | `world.Query()` items | `item.Position`, `item.Velocity` | ```csharp unit.SetPosition(3, 4).SetDead(); // setters return the entity unit.Position.X += 1; // untracked: a ref unit.SetHealth(80); // tracked: written with Set, stamped bool dead = unit.IsDead; ``` Guide: [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components). ## Systems and [ForEach] ```csharp public class MovementSystem : EcsSystem { [ForEach, Without] // once per entity with Position and Velocity, without Dead static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y); } ``` ### [ForEach] parameters | Parameter | Is | Notes | | --------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `ref T` | A component the method writes | 1 to 9 components; a write for change tracking | | `in T` | A component the method reads | Not a write ([EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) catches writes through `in`) | | `Span` / `ReadOnlySpan` | A run of rows of `T` (a batch method) | Cannot mix with per-entity parameters ([EECS009](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs009)) | | `ref S` / `in S` | A singleton | Resolved once per pass; throws if it was not added | | `Entity` | The current entity | Use it for structural changes | | `World` | The world | For creating entities from a static method | | `EntitySpan` | The entities of a batch method's run | Batch methods only | | `Maybe` | A component the entity may lack | `HasValue`, `Value` | | Any other type (outside a system) | A value the caller passes to the entry point | `ref int count`, `in Settings s` | ### Attributes | Attribute | On | Does | | ------------------------------------------ | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | | `[ForEach]` / `[ForEach(Parallel = true)]` | Method | The method is the loop; `Parallel` splits rows across threads ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010)) | | `[With]` | Method, system group | Requires `T` without passing it | | `[Without]` | Method, system group | Excludes entities with `T` | | `[WithAny, WithAny]` | Method, system group | Requires at least one of them | | `[Changed]` | Method | Rows whose tracked `T` was written since the system last ran | | `[Removed]` | Method | Entities that lost tracked `T` since the system last ran | | `[UpdateBefore]` / `[UpdateAfter]` | System | Ordering ([EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019) rejects cycles) | | `[UpdateInGroup]` | System | Runs on `world.Update()` only | `[Changed]` and `[Removed]` go on methods only. A system group takes `[With]`, `[Without]` and `[WithAny]` ([EECS023](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs023) flags them on any other struct), or `IGroupWith` / `IGroupWithout`, which a generic group interface needs because an attribute cannot name a type parameter: ```csharp public struct In : IComponent; // the tag of one actor type public interface IActorGroup : IGroupWith> where TActor : struct; public struct Shop : IActorGroup; // the systems of [UpdateInGroup] see In entities only ``` ### System members | Member | Does | | ------------------------------------------- | ---------------------------------------------------------------- | | `OnCreate()` / `OnUpdate()` / `OnDestroy()` | Lifecycle; `OnUpdate` runs before the `[ForEach]` methods | | `World` | The system's world | | `UpdateInterval` / `UpdatePhase` | Run every N-th update, on phase 0 to N-1 | | `Enabled` | Skip the system; setting `true` clears `Error` | | `Error` | The exception that disabled it under `SystemErrorPolicy.Disable` | | `LastRunTick` | The change tick of its last run | | `Stats` | `Runs`, `Last`, `Total`, `Average` with `MeasureSystems` | Systems keep no state ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007)) and never reference each other ([EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008)). Guide: [Systems](https://ecs.xgamedev.net/en/docs/guide/systems). ## Queries and filters ```csharp // A field: build each filter once. private static readonly QueryFilter Alive = QueryFilter.Create().Without(); ``` ```csharp foreach (var item in world.Query(Alive)) item.Position.X += item.Velocity.X; // items hand out refs; item.Entity is the handle int movers = world.Count(Alive); bool anyDead = world.Any(); ``` | Call | Does | | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `world.Query(filter)` | `foreach` over items: `ref` components and `Entity` | | `world.Count(filter)` / `Any<…>(filter)` | Counts, or stops at the first match | | `world.ForEach(ref job, filter)` | A struct job `IForEach`: `Execute(ref T1 …)` | | `world.ForEachEntity<…>(ref job, filter)` | `IForEachEntity`: `Execute(Entity e, ref T1 …)` | | `world.ForEachBatch<…>(ref job, filter)` | `IForEachBatch`: runs of rows as spans | | `world.ForEachParallel` / `ForEachEntityParallel` | A struct job in chunks on several threads | | `Runner.Method(world, …)` | The entry point of a static `[ForEach]` method outside a system | | `static int Writes => mask` on a job | Components the job writes (bit k - 1 for component k), stamped for change tracking; default `-1`, all | | `: INoStructuralChanges` on a job | The job promises no structural change: no per-entity bookkeeping, structure frozen while it runs | | `QueryFilter` | Selects | | ------------------------------------------------ | ------------------------------------------ | | `.With()` / `.Without()` / `.WithAny()` | Presence, as the attributes | | `.Changed(since)` / `.Removed(since)` | Written, or lost, at or after tick `since` | | `.Since(tick)` | The same filter with a new tick | | `.InGroup(group)` | One group of a grouped component | Guide: [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries). ## Singletons | Call | Does | | ----------------------------------------------------------------------------------- | -------------------------------------------- | | `world.AddSingleton()` | Adds (or resets to default), returns `ref T` | | `world.GetSingleton()` / `GetOrAddSingleton()` | `ref T`; the first throws when missing | | `world.TryGetSingleton(out copy)` / `HasSingleton()` / `RemoveSingleton()` | Copy, presence, removal | | `world.SingletonRef()` | A stable handle: `.Value` is `ref T` | ```csharp world.SetClock(0); // generated: adds it if missing world.Clock.Tick++; ``` Guide: [Singletons](https://ecs.xgamedev.net/en/docs/guide/singletons). ## Change tracking | Is a write | Is not a write | | ---------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | `ref` parameters, `Span`, `Query` items | `in` parameters, `ReadOnlySpan` | | `Get()`, `TryGetRef` when found, `GetOrAdd()`, `Set(…)`, `WriteX()` | `Read()`, `TryGet(out copy)`, `Has()`, `e.X` of a tracked `X` | | Creating, instantiating, cloning, `Restore`, `Load`, `LoadEntitiesInto` | Removing (that is a removal, for `[Removed]`) | | `entity.Run`: the components in the job's `Writes` | `LoadEntitiesInto(…, markWritten: false)` | ```csharp ulong mark = world.ChangeTick; world.Update(); int changed = world.Count(QueryFilter.Create().Changed(mark)); ``` Guide: [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking). ## Indexes, relations, hierarchy, groups | Call | Does | | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `world.Index()` (`world.TIndex`) | The value index of `T` | | `index.Find(key)` / `TryFind(key, out e)` / `Count(key)` | Matching entities, one, how many | | `index.Range(min, max)` / `RangeDescending` / `Ascending()` / `Descending()` | Sorted walks, for a comparable key | | `index.WhenTargetDestroyed(TargetPolicy.Keep / Remove / Destroy)` | What an `EntityId` link does when its target dies | | `entity.AddRelation(r)` / `RemoveRelation(target)` / `HasRelation(target)` | Many-to-many links | | `world.Relations()` then `Find(target)` / `Count(target)` | Who links to a target | | `world.Children(parent)` | Entities whose `ChildOf` names the parent; destroying the parent destroys them (`ChildOf` starts with `TargetPolicy.Destroy`) | | `world.Descendants(root)` | The whole subtree, depth first, each entity before its children, root excluded; a `ChildOf` cycle throws `InvalidOperationException` | | `world.GroupBy()` | Splits tables by an `IGroup` value | ```csharp var teams = world.TeamIndex; foreach (var member in teams.Find(1)) member.SetTeam(2); // write indexed components with Set var ship = world.CreateEntity(); world.CreateEntity(new ChildOf(ship)); foreach (var child in world.Children(ship)) { } foreach (var part in world.Descendants(ship)) { } // children, grandchildren, ... ``` Indexed and grouped components are written with `Set`, never through a `ref` ([EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015)). Guides: [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations), [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy), [Groups](https://ecs.xgamedev.net/en/docs/guide/groups). ## Prefabs and bulk operations | Call | Does | | --------------------------------------------------------- | ----------------------------------------------------------------------- | | `new Prefab().SetX(…)…` / `new Prefab(basePrefab)` | A recipe outside every world, or a variant of one | | `prefab.AddMember()` / `prefab.Id` | A group of entities instantiated together; `Id` names a member in links | | `prefab.SetBuffer(items)` | A `DynamicBuffer` each instance gets a copy of | | `world.Instantiate(prefab)` / `Instantiate(prefab, span)` | One entity, or a wave in one pass | | `world.CreateEntities(span, a, b, …)` | A wave with the same values | | `world.DestroyEntities(filter)` | Destroys every match; returns how many | | `world.SetAll(value, filter)` / `RemoveAll(filter)` | One component set or removed on every match | | `world.DisableAll(filter)` / `EnableAll(filter)` | One component disabled or enabled on every match | ```csharp var goblin = new Prefab().SetPosition(0, 0).SetHealth(30); var wave = new Entity[100]; world.Instantiate(goblin, wave); world.SetAll(new Velocity(0, 0), QueryFilter.Create().With()); world.DestroyEntities(); ``` Guides: [Prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs), [Bulk operations](https://ecs.xgamedev.net/en/docs/guide/bulk). ## Dynamic buffers Reads go through `e.Loot` (`ref readonly`, with `Count`, `Capacity`, an indexer and `foreach`); writes take the buffer by `ref` from `e.WriteLoot()` (or `GetOrAddLoot()`), so each one counts for change tracking. | Call on `ref DynamicBuffer` | Does | | ------------------------------------------------------- | ------------------------------------------------------------------ | | `Add(item)` / `AddRange(items)` / `Insert(index, item)` | Appends, appends a span, inserts | | `RemoveAt(index)` / `RemoveAtSwapBack(index)` | Removes keeping the order, or by moving the last element in (O(1)) | | `Clear()` | Empties it, keeping the capacity | | `EnsureCapacity(n)` / `TrimExcess()` | Grows once before a known count, gives memory back | | `AsSpan()` | A `Span` over the elements, for writes in place | ```csharp unit.Set(new DynamicBuffer()); ref var loot = ref unit.WriteLoot(); loot.EnsureCapacity(8); loot.Add(new Loot(7)); loot.RemoveAtSwapBack(0); ``` Guide: [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers). ## Snapshots, saves, migration | Call | Does | | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `world.Capture()` / `Capture(into)` | An in-memory copy; `into` reuses a snapshot's arrays | | `world.Restore(snapshot)` | Back to the copy; handles from then are valid again | | `world.Save(writer)` / `Load(bytes)` | A whole world as bytes (managed components need `[NinoType]`); `Load` throws `InvalidDataException` when an unmanaged component's layout changed since the save | | `world.SaveEntities(writer, ids)` / `LoadEntities(bytes, handles)` | A group of entities to another world or process | | `ComponentSet.Create().With()…` | The components of a record, built once in a `static readonly` field | | `world.SaveEntities(writer, ids, set)` | A record: only the components of the set | | `world.LoadEntitiesInto(bytes, entities, markWritten: false)` | A record onto entities that exist; `markWritten: false` keeps it from counting as changed | | `world.MoveEntities(target, ids, moved)` | A group to another world of the thread, no encoding | | `world.RemoveTypes(assembly or context)` | Drops a plugin's types before its context unloads | ```csharp var save = world.Capture(); world.Update(); world.Restore(save); var bytes = new System.Buffers.ArrayBufferWriter(); world.Save(bytes); using var copy = new World(); copy.Load(bytes.WrittenSpan); ``` Guides: [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots), [Saves](https://ecs.xgamedev.net/en/docs/guide/saves), [Migration and unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records). ## World options | `WorldOptions` | Default | Does | | ------------------------ | ------------------------- | ----------------------------------------------------------- | | `InitialEntityCapacity` | 1024 | Entity records allocated up front | | `ParallelSystems` | `false` | Runs systems with no order and no conflict at the same time | | `MaxDegreeOfParallelism` | processor count | Threads one parallel run uses at most | | `MeasureSystems` | `false` | Records `system.Stats` | | `SystemErrors` | `SystemErrorPolicy.Throw` | `Disable` switches a failing system off and goes on | ```csharp using var server = new World(new WorldOptions { ParallelSystems = true, SystemErrors = SystemErrorPolicy.Disable }); ``` Guide: [Threading](https://ecs.xgamedev.net/en/docs/guide/threading). Running it in a server and checking it: [Hosting](https://ecs.xgamedev.net/en/docs/guide/hosting), [Testing systems](https://ecs.xgamedev.net/en/docs/guide/testing), [Debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics). ## Related - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): The same API, step by step, in a running simulation. - [Glossary](https://ecs.xgamedev.net/en/docs/glossary): Every term on this page in one or two sentences. - [API and complexity](https://ecs.xgamedev.net/en/docs/api): Every public API with its complexity. --- # Example: a battle server > A complete battle server built with EasyEcs, section by section: components, prefabs, systems, replication by change tracking, indexes, relations and saves. URL: https://ecs.xgamedev.net/en/docs/example Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/example.md A battle server that uses every feature of EasyEcs the way it is meant to be used: plain data, one job per system, systems that never know about each other, and a host that ticks the world and answers questions between ticks. This page walks through it section by section. Every code block on it is included from [`BattleServer.cs`](https://github.com/JasonXuDeveloper/EasyEcs/blob/master/benchmarks/EasyEcs.Benchmark/BattleServer.cs), the same file that `BattleServerBenchmark` measures and [`BattleServerTests`](https://github.com/JasonXuDeveloper/EasyEcs/blob/master/tests/EasyEcs.UnitTest/BattleServerTests.cs) checks feature by feature, so what you read here is the code that runs. ## What the world simulates A battle of `units` entities, a third of them players and the rest NPCs, on a 4,096 × 4,096 map split into four zones: - NPCs steer towards waypoints; every unit moves, attacks on a cooldown, and may catch fire or freeze. - A unit whose health reaches zero dies. Players respawn next to a living friend; an NPC drops loot for a player of its zone and comes back later as a new NPC. - Players spend mana on projectiles that fly for twenty ticks and belong to their shooter. - Every third tick the server replicates what changed: healths, fires that started or went out, bags of loot. - Between ticks the host answers questions: a census, the nearest player, the top killers, a save, a rollback. One call to `Tick()` runs the default group of systems, in this order, and the `Replication` group every third tick: ```mermaid flowchart LR M["Steering, movement,
mana, zones"] --> F["Combat, statuses,
afflictions, deaths"] F --> R["Respawn, despawn,
revive"] R --> P["Projectiles,
regeneration"] P --> C[Clock] C -->|every third tick| Rep["Replication group"] ``` With `ParallelSystems` on, systems with no order and no conflicting access between them share a stage and run at once (`MovementSystem` and `ManaSystem` touch different components); the result is the same as running them one after the other. ## Where each feature is Coming from another ECS? [Comparison](https://ecs.xgamedev.net/en/docs/comparison) maps their features to EasyEcs; this table maps EasyEcs' features to their place in this file. | Feature | Where | | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Components, tags, singletons](https://ecs.xgamedev.net/en/docs/guide/entities-and-components) | `Position`, `Health`, `Player`, `Dead`; singletons `Battle`, `Rules`, `Waypoints` | | Generated members | `players[i].Position = …`, `SetZone`, `SetFrozen`, `RemoveBurning`, `SetDead`, `IsDead`, `TryGetMana`, `WriteHealth()`, `World.Battle`, `KillsIndex`; buffers `player.Loot`, `WriteLoot()`; `DisableAttack` / `EnableAttack`; on prefabs `SetHealth`, `SetNpc` | | [Systems](https://ecs.xgamedev.net/en/docs/guide/systems), filters (`With`, `Without`, `WithAny`) | every system; `AfflictionSystem` counts burning **or** frozen units with `World.Count` | | [Parallel `[ForEach]`](https://ecs.xgamedev.net/en/docs/guide/threading) | `SteeringSystem`; `Reports.HealFully` and `Reports.Scatter` in `NewRound` | | Parallel systems (`WorldOptions.ParallelSystems`) | `MovementSystem` and `ManaSystem`: disjoint data | | Batch methods (`Span`), SIMD | `MovementSystem`; `Reports.SumHealth` | | `[ForEach]` runners outside systems | `Reports` | | `Maybe` | `RegenerationSystem` heals burning players less | | [Disabling components](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) | a frozen unit's `Attack` and `Velocity`; `NewRound` enables them all in bulk | | [Cleanup components](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) (`ICleanupComponent`, `Destroyed`) | `Spawn`: a destroyed NPC leaves it behind for `RespawnSystem.Revive` | | [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy) (`ChildOf`, `Children`, `Descendants`) | projectiles are children of their player; `Transfer` collects the subtree | | [Structural changes during passes](https://ecs.xgamedev.net/en/docs/guide/structural-changes) | statuses, deaths, respawns, projectiles spawned and destroyed mid-pass | | [Prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs) (`Prefab`, `Instantiate`, `EnsureCapacity`), cloning | `Hero`, `Grunt`, `Brute` (a variant of `Grunt`); `Mirror` clones a living unit | | [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking) and removal detection | `ReplicationSystem`; `WrittenSinceCheckpoint` | | [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) | every player's bag of `Loot` | | [Groups](https://ecs.xgamedev.net/en/docs/guide/groups) (`IGroup`, `GroupBy`, `InGroup`) | `Zone`: a table per zone | | [Ordered index, relations, target policies](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) | `Kills` leaderboard; `Friend` links, dropped when a player leaves | | System groups, `UpdateInterval`, `UpdatePhase`, ordering, lifecycle | `Replication`; `ManaSystem`, `RegenerationSystem`; `ClockSystem`; `SteeringSystem.OnCreate` | | [Queries](https://ecs.xgamedev.net/en/docs/guide/queries), handles and [one-entity jobs](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity) | `NearestPlayer`, `Census`, `ShotsLeft`; `Hit` runs the `TakeHit` job with `entity.Run` | | [Bulk operations](https://ecs.xgamedev.net/en/docs/guide/bulk) | `Instantiate(prefab, span)`, `DestroyEntities`, `RemoveAll`, `EnableAll` | | [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots), [saves and moves](https://ecs.xgamedev.net/en/docs/guide/saves) | `Checkpoint` / `Rewind`, `Save` / `Load`, `Transfer` | | Introspection, diagnostics, error policy | `Tables`, `Slowest`, `Failure` | ## The data ### Components Every component is a plain `record struct`. Three markers change how the world stores one: `ITrackChanges` gives it a hidden column of change ticks (`Health` and `Burning` are replicated), `IGroup` splits tables by its value (one table set per `Zone`), and `IIndexed` keeps a value index of it (`Kills`, the leaderboard). `Spawn` is a cleanup component, `Loot` and `Friend` are the elements of dynamic buffers, and the empty structs are tags. ```csharp public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; public record struct Health(int Value, int Max) : IComponent, ITrackChanges; // replicated: writes are tracked public record struct Replica(int Health, bool Burning) : IComponent; // what clients last received public record struct Mana(int Value, int Max) : IComponent; public record struct Attack(int Damage, int Interval, int Cooldown) : IComponent; public record struct Burning(int Ticks) : IComponent, ITrackChanges; // status effects come and go; clients // see fires start and go out public record struct Frozen(int Ticks) : IComponent; // while it lasts, Attack and Velocity // are disabled: no query sees them public record struct Lifetime(int Ticks) : IComponent; public record struct Zone(int Id) : IComponent, IGroup { public int Group => Id; } // a table per zone public record struct Kills(int Count) : IComponent, IIndexed { public int Key => Count; } // ordered: a leaderboard public record struct Spawn(Position At, int Seed) : ICleanupComponent; // outlives its NPC: where the next appears public record struct Loot(int Item); // players carry a DynamicBuffer public record struct Friend(EntityId Target) : IRelation; // and a DynamicBuffer of links public struct Player : IComponent; // tags: empty components public struct Npc : IComponent; public struct Dead : IComponent; ``` ### Singletons and a system group State that exists once per battle is a singleton: `Battle` counts what happened, `Rules` holds the battle's rules as data, and `Waypoints` is a fixed-size array the steering reads. `Replication` is an empty struct that names a system group, updated by its own call. ```csharp public record struct Battle(long Tick, int Hits, int Deaths, int Shots, int Replicated, int Afflicted) : ISingletonComponent; public record struct Rules(int ShotCost, int BagSize, bool Ceasefire) : ISingletonComponent; // the battle's rules: data public struct Waypoints : ISingletonComponent { public const int Count = 8; public WaypointArray Points; } [InlineArray(Waypoints.Count)] public struct WaypointArray { private Position _first; } public struct Replication : ISystemGroup; // runs when the server sends updates ``` ## The systems Each system does one job and shares nothing with the others but components and singletons. `ref` marks what a `[ForEach]` method writes and `in` what it reads; the generator builds the loop and the access set from those two words. ### Moving `SteeringSystem` is heavy per-entity math, so it runs on every core (`Parallel = true`); it creates the `Waypoints` singleton it reads in `OnCreate` and removes it in `OnDestroy`. `MovementSystem` takes spans and adds whole runs of rows as `Vector`. `ManaSystem` runs every tenth update, five updates after `RegenerationSystem`, so their work falls on different ticks. `ZoneSystem` writes `Zone` only when a unit really changes zone, which moves its row to the zone's table. ```csharp public class SteeringSystem : EcsSystem // heavy per-entity math: on all cores { protected override void OnCreate() // the system sets up the data it steers by { ref var waypoints = ref World.GetOrAddWaypoints(); for (int i = 0; i < Waypoints.Count; i++) waypoints.Points[i] = new Position(512 + i * 400, 512 + i * 1777 % 3000); } protected override void OnDestroy() => World.RemoveWaypoints(); [ForEach(Parallel = true), With, Without, Without] static void Steer(in Position p, ref Velocity v, in Waypoints waypoints) { var target = waypoints.Points[(int)(p.X + p.Y) & (Waypoints.Count - 1)]; float dx = target.X - p.X, dy = target.Y - p.Y, length = MathF.Sqrt(dx * dx + dy * dy) + 1; v = new Velocity(dx / length * 2, dy / length * 2); } } public class MovementSystem : EcsSystem { [ForEach, Without] // whole runs of rows, vectorized static void Move(Span positions, ReadOnlySpan velocities) { // Two floats each, no padding: as Vector spans, every lane is one coordinate (the JIT does not // vectorize loops by itself) var p = MemoryMarshal.Cast>(positions); var v = MemoryMarshal.Cast>(velocities); for (int i = 0; i < p.Length; i++) p[i] += v[i]; var pf = MemoryMarshal.Cast(positions); var vf = MemoryMarshal.Cast(velocities); for (int i = p.Length * Vector.Count; i < pf.Length; i++) pf[i] += vf[i]; // the rows left over } } public class ManaSystem : EcsSystem // other data than MovementSystem: both { // run at once public override int UpdateInterval => 10; // every 10th update, five updates after public override int UpdatePhase => 5; // RegenerationSystem: their work spreads [ForEach] static void Regenerate(ref Mana mana) => mana.Value = Math.Min(mana.Max, mana.Value + 10); } public class ZoneSystem : EcsSystem // a new zone moves the row to its table { [ForEach] static void Enter(Entity player, in Position p, in Zone zone) // `in`: reading is not a change { int id = Math.Clamp((int)(p.X / 1024), 0, 3); if (zone.Id != id) player.SetZone(id); // only real moves are writes } } ``` ### Fighting Combat is split into damage (`CombatSystem`) and statuses (`StatusSystem`). Freezing a unit disables its `Attack` and `Velocity`: the values are kept, but no query sees them until `Thaw` enables them again, so a frozen unit neither attacks, moves nor shoots without any system checking for `Frozen`. `AfflictionSystem` counts burning or frozen units without a loop: `Count` reads presence bits 64 rows at a time. `DeathSystem` marks the dead with a tag that other systems filter on. ```csharp public class CombatSystem : EcsSystem // damage only: statuses are StatusSystem's { [ForEach, Without] // a frozen unit's Attack is disabled static void Fight(Entity unit, ref Attack attack, ref Battle battle) { if (--attack.Cooldown > 0) return; attack.Cooldown = attack.Interval; unit.WriteHealth().Value -= attack.Damage; // a hit is a change of Health battle.Hits++; } } public class StatusSystem : EcsSystem { [ForEach, Without] // the units that attacked this tick static void Afflict(Entity unit, in Attack attack, in Battle battle) { if (attack.Cooldown != attack.Interval) return; // CombatSystem just reset it uint roll = Dice.Roll(battle.Tick, unit.Id.Index); if (roll % 50 == 0) unit.GetOrAddBurning() = new Burning(10); // applied at once; a new fire restarts it else if (roll % 70 == 1) { unit.SetFrozen(4); unit.DisableAttack(); // kept, but no query sees them: no attacks, unit.DisableVelocity(); // no steering, no moves, no shots } } [ForEach] static void Burn(Entity unit, ref Burning burning, ref Health hp) { hp.Value -= 3; if (--burning.Ticks == 0) unit.RemoveBurning(); // flips a bit: the row stays } [ForEach] static void Thaw(Entity unit, ref Frozen frozen) { if (--frozen.Ticks > 0) return; unit.RemoveFrozen(); unit.EnableAttack(); // back with the values they had unit.EnableVelocity(); } } public sealed class AfflictionSystem : EcsSystem // registered after StatusSystem { // A count, not a loop: Count reads presence bits, 64 rows per load protected override void OnUpdate() => World.Battle.Afflicted += World.Count(BattleServer.Afflicted); } public class DeathSystem : EcsSystem { [ForEach, Without] // a plain scan: most healths change often static void Die(Entity unit, in Health hp, ref Battle battle) { if (hp.Value > 0) return; unit.SetDead(); // whoever cares queries Dead battle.Deaths++; } } ``` ### Death and respawn `RespawnSystem` reacts to the `Dead` tag; `DeathSystem` does not know it exists. A player recalls its projectiles (its children), empties its bag, comes back next to a living friend found through its `Friend` links, and loses its statuses in one `Remove()`. An NPC writes where the next one should appear into its `Spawn` cleanup component, gives its loot to a player of its zone (one group's table to look at) and is destroyed: its `Spawn` stays behind with the `Destroyed` tag until `Revive` spawns the next NPC and removes it, which frees the old entity. ```csharp public class RespawnSystem : EcsSystem // DeathSystem does not know it exists { [ForEach, With, With] static void Respawn(Entity player, ref Health hp, ref DynamicBuffer bag, World world) { foreach (var shot in world.Children(player)) shot.Destroy(); // recall its projectiles hp.Value = hp.Max; bag.Clear(); // a death empties the bag var at = new Position(2048, 2048); foreach (var link in player.Friend) // next to a living friend, if any if (world.TryGetEntity(link.Target, out var friend) && !friend.IsDead) { at = friend.Position; break; } player.Set(at, new Mana(0, 100), new Kills(0)); // several components, one call; a death // ends the kill streak player.Remove(); // back without statuses: one transition player.EnableAttack(); // false when it was not frozen player.EnableVelocity(); } [ForEach, With, With] static void Despawn(Entity npc, in Position p, ref Spawn spawn, in Rules rules, World world) { spawn = new Spawn(new Position(p.Y, p.X), npc.Id.Index); // where the next one appears Entity hunter = default; foreach (var item in world.Query(BattleServer.Zones[npc.Id.Index & 3])) // a player of some zone: { // one table to look at hunter = item.Entity; spawn.At = item.Position; break; } if (hunter.IsAlive) { ref var bag = ref hunter.WriteLoot(); // the hunter gets the loot if (bag.Count == rules.BagSize) bag.RemoveAt(0); // a full bag drops its oldest item bag.Add(new Loot(npc.Id.Index & 15)); hunter.SetKills(hunter.Kills.Count + 1); // the leaderboard follows } npc.Destroy(); // Spawn stays, with the Destroyed tag } [ForEach, With] // what destroyed NPCs left behind static void Revive(Entity old, in Spawn spawn, World world) { BattleServer.SpawnNpc(world, spawn.At, spawn.Seed); old.RemoveSpawn(); // its last cleanup component: freed } } ``` ### Projectiles, regeneration and the clock A projectile is an entity with a `ChildOf` link to its player, so destroying the player destroys its shots. `RegenerationSystem` heals burning players less with one method: `Maybe` tells whether this entity has the component. `ClockSystem` is registered first but runs last, because `[UpdateAfter]` moves it. ```csharp public class ProjectileSystem : EcsSystem { [ForEach, With, Without] // a frozen player's Velocity is disabled static void Shoot(Entity player, in Position p, in Velocity v, ref Mana mana, ref Battle battle, in Rules rules, World world) { if (rules.Ceasefire || mana.Value < rules.ShotCost || Dice.Roll(battle.Tick, player.Id.Index) % 20 != 0) return; mana.Value -= rules.ShotCost; battle.Shots++; world.CreateEntity(p, new Velocity(v.X * 4, v.Y * 4), new Lifetime(20), new ChildOf(player)); // a child: gone } // with its player [ForEach] static void Expire(Entity shot, ref Lifetime life) { if (--life.Ticks == 0) shot.Destroy(); } } public class RegenerationSystem : EcsSystem { public override int UpdateInterval => 10; // every 10th update [ForEach, With, Without] static void Regenerate(Entity player, in Health hp, Maybe burning) // burning or not: one method { if (hp.Value < hp.Max) player.WriteHealth().Value = Math.Min(hp.Max, hp.Value + (burning.HasValue ? 5 : 20)); } } [UpdateAfter] // registered first, runs last public sealed class ClockSystem : EcsSystem { protected override void OnCreate() => World.GetOrAddBattle(); protected override void OnUpdate() => World.Battle.Tick++; } ``` ## Replication by change tracking `ReplicationSystem` belongs to the `Replication` group, which the host updates every third tick. Each method visits only what changed since the system last ran: the healths written (`[Changed]`), the units set on fire (`[Changed]`), the fires that went out (`[Removed]`, the entities that lost the component and still lack it) and the bags written through a `ref` (`[Changed>]`). Nothing marks rows dirty by hand: a write through a `ref` is the mark. ```csharp [UpdateInGroup] public class ReplicationSystem : EcsSystem // only what changed since the last send { [ForEach, Changed] static void Send(in Health hp, ref Replica replica, ref Battle battle) { replica.Health = hp.Value; battle.Replicated++; } [ForEach, Changed] // set on fire, or burning on static void SendFire(ref Replica replica, ref Battle battle) { if (replica.Burning) return; replica.Burning = true; battle.Replicated++; } [ForEach, Removed] // the fire went out: the row lacks it now static void SendFireOut(ref Replica replica, ref Battle battle) { if (!replica.Burning) return; // lit and out between two sends replica.Burning = false; battle.Replicated++; } [ForEach, Changed>] // bags changed by a ref write static void SendBag(in DynamicBuffer bag, ref Battle battle) => battle.Replicated += 1 + bag.Count; } ``` Why it pays and what counts as a write: [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking) and [removal detection](https://ecs.xgamedev.net/en/docs/guide/change-tracking#removal-detection). ## Passes outside the tick A static `[ForEach]` method of an ordinary static class is a runner: the generator writes an entry point that takes the world and the method's other arguments (`Reports.SumMana(world, ref total)`). The host calls them between ticks. `SumHealth` reads whole runs of rows as `Vector` lanes; `HealFully` and `Scatter` run in parallel chunks. `Dice` is a pure function of the tick and the entity, so a roll is the same on any thread. ```csharp public static class Dice { public static uint Roll(long tick, int id) { ulong x = (ulong)tick * 0x9E3779B97F4A7C15UL ^ (uint)id * 0xBF58476D1CE4E5B9UL; x ^= x >> 31; x *= 0x94D049BB133111EBUL; return (uint)(x ^ (x >> 29)); } } /// /// [ForEach] methods outside systems: the generator writes the job and an entry point taking the world and the /// caller's values (Reports.SumMana(world, ref total)), for passes the host runs between ticks. /// public static class Reports { [ForEach, With, Without] // whole runs of rows, read-only static void SumHealth(ReadOnlySpan hp, ref long total) { // Value, Max, Value, Max, ...: sum every lane, keep the even ones (an int lane holds 4M rows of 500) var lanes = MemoryMarshal.Cast>(hp); var sum = Vector.Zero; for (int i = 0; i < lanes.Length; i++) sum += lanes[i]; total += Vector.Sum(sum & Vector.Equals(Vector.Indices & Vector.One, Vector.Zero)); for (int i = lanes.Length * Vector.Count / 2; i < hp.Length; i++) total += hp[i].Value; // left over } [ForEach] static void SumMana(in Mana mana, ref long total) => total += mana.Value; [ForEach, With, Without] static void FindWeakest(Entity player, in Health hp, ref EntityId weakest, ref int lowest) { if (hp.Value < lowest) (lowest, weakest) = (hp.Value, player); } [ForEach(Parallel = true)] // chunks on all cores: no shared state static void HealFully(ref Health hp) => hp.Value = hp.Max; [ForEach(Parallel = true), With] // NPCs start the round anywhere static void Scatter(Entity npc, ref Position p, long round) { uint r = Dice.Roll(round, npc.Id.Index); // per entity, the same on any thread p = new Position(r % 4096, (r >> 12) % 4096); } } /// What the server reports: computed by the runners of , outside the tick. public record struct Census(int Players, int Alive, long Health, long Mana, Entity Weakest, int ReadyToAttack); ``` ## The host `BattleServer` owns one world on one thread, ticks it, and answers questions about it between ticks. ### Filters and prefabs Filters are built once, in `static readonly` fields; `WrittenPlayers` takes its tick per call with `Since`. The prefabs are recipes that belong to no world, so no query sees them: `Hero` sets its components several at once or one by one through the generated writers, and `Brute` is a variant, a copy of `Grunt` with three values changed. ```csharp public const int ShotCost = 30; public const int BagSize = 8; private static readonly QueryFilter Players = QueryFilter.Create().With(); // build filters once private static readonly QueryFilter AlivePlayers = Players.Without(); private static readonly QueryFilter Alive = QueryFilter.Create().Without(); internal static readonly QueryFilter Afflicted = QueryFilter.Create().WithAny().WithAny(); private static readonly QueryFilter WrittenPlayers = Players.Changed(0); // the tick is set per call internal static readonly QueryFilter[] Zones = // one table each [Players.InZone(0), Players.InZone(1), Players.InZone(2), Players.InZone(3)]; // Unit kinds: recipes that belong to no world (no query sees them), copied by Instantiate private static readonly Prefab Hero = new Prefab().Set(new Position(), new Velocity(1, 0)) // several at once .SetHealth(500, 500).SetReplica(500, false).SetMana(100, 100).SetAttack(8, 6, 0) // or one by name .SetZone(0).SetKills(0).SetPlayer().Set(new DynamicBuffer()) .SetLoot(new Loot(0)); // a starter item: each hero gets a bag of its own private static readonly Prefab Grunt = new Prefab().Set(new Position(), new Velocity()) .SetHealth(120, 120).SetReplica(120, false).SetAttack(6, 8, 0).SetSpawn(default, 0).SetNpc(); private static readonly Prefab Brute = new Prefab(Grunt) // a variant: a copy .SetHealth(200, 200).SetReplica(200, false).SetAttack(9, 12, 0); ``` ### Setting up the world The constructor configures the world (parallel systems, timings, a failing system switched off instead of thrown), groups tables by `Zone`, sets the friend links' target policy, registers the systems in tick order and spawns the units in bulk: one table growth per wave. `EnsureCapacity` sizes the NPC tables for respawn waves, so they never grow during a tick. ```csharp public readonly World World; private readonly SingletonRef _battle; // resolved once, no lookup per tick private readonly List _group = []; // reused by Transfer private WorldSnapshot _checkpoint; private ulong _checkpointAt; /// A battle of units, a third of them players. public BattleServer(int units) { World = new World(new WorldOptions { InitialEntityCapacity = units * 2, ParallelSystems = true, // unordered systems with disjoint data side by side MeasureSystems = true, // per-system timings in system.Stats SystemErrors = SystemErrorPolicy.Disable, // a failing system goes off, the battle goes on }); World.GroupBy(); // a zone's players contiguous, in its table World.FriendIndex.WhenTargetDestroyed(TargetPolicy.Remove); // a player who leaves leaves friend lists World.SetRules(ShotCost, BagSize, false); World.AddSystem(); // OnCreate adds the Battle singleton World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); World.AddSystem(); _battle = World.SingletonRef(); var players = new Entity[units / 3]; World.Instantiate(Hero, players); // in bulk: one table growth for (int i = 0; i < players.Length; i++) { uint r = Dice.Roll(0, i); players[i].Position = new Position(r % 4096, (r >> 12) % 4096); players[i].Velocity = new Velocity((int)(r % 5) - 2, (int)((r >> 8) % 5) - 2); players[i].Attack.Cooldown = (int)(r % 6); players[i].WriteLoot().EnsureCapacity(BagSize); // room once: a full bag never grows players[i].AddFriend(players[(i + 1) % players.Length]); // each player has two friends players[i].AddFriend(players[(i + 7) % players.Length]); } var npcs = new Entity[units - players.Length]; World.Instantiate(Grunt, npcs.AsSpan(0, npcs.Length / 2)); // copies of a recipe, in bulk World.Instantiate(Brute, npcs.AsSpan(npcs.Length / 2)); for (int i = 0; i < npcs.Length; i++) { uint r = Dice.Roll(0, players.Length + i); npcs[i].Position = new Position(r % 4096, (r >> 12) % 4096); npcs[i].Attack.Cooldown = (int)(r % 10); } World.EnsureCapacity(Grunt, npcs.Length / 4); // respawn waves never grow the tables World.EnsureCapacity(Brute, npcs.Length / 4); } public static void SpawnNpc(World world, Position at, int seed) { uint r = Dice.Roll(seed, seed); var npc = world.Instantiate((r & 1) == 0 ? Grunt : Brute); // then only what differs is written npc.Position = at; npc.Attack.Cooldown = (int)(r % 10); } ``` ### The tick `Tick()` is two calls. `Battle` reads the counters through a `SingletonRef`, resolved once. `Failure` finds a system that threw: under `SystemErrorPolicy.Disable` the exception is data in `system.Error`, and the battle goes on. `Ceasefire` is a rule, so changing it is a write to a singleton, not a call into a system. ```csharp public ref Battle Battle => ref _battle.Value; /// A system that threw: it was switched off and the battle went on (its Error is the failure, as data). public EcsSystem Failure { get { foreach (var system in World.Systems) if (system.Error != null) return system; return null; } } /// One server tick: the simulation every tick, replication every third. public void Tick() { World.Update(); if (Battle.Tick % 3 == 0) World.Update(); } /// Whether players hold fire: a rule of the battle is data, so shots in flight still expire. public bool Ceasefire { get => World.Rules.Ceasefire; set => World.Rules.Ceasefire = value; } ``` ### Questions between ticks `PlayersIn` counts one group's table. `Any` stops at the first match. `ShotsLeft` and `Hit` start from a handle or an id a client sent: a stale one answers false. `Hit` is a request on one unit, so it runs a job with `entity.Run`: one lookup for the job's components, and the `Alive` filter turns a dead unit away. The job declares that it writes `Health`, so the hit is stamped for the next replication. ```csharp public int PlayersIn(int zone) => World.Count(Zones[zone]); // one table: its rows, not a scan public bool AnyoneBurning => World.Any(); public bool AnyoneAfflicted => World.Any(Afflicted); // burning or frozen public int ShotsLeft(Entity player) => player.IsAlive && player.TryGetMana(out var mana) ? mana.Value / ShotCost : 0; /// /// A client's hit on the unit it names by id: the id turns back into a handle if that unit still lives, and the hit /// runs as a job on that one unit. /// public bool Hit(EntityId target, int damage) { var hit = new TakeHit(damage); return World.TryGetEntity(target, out var unit) && unit.Run(ref hit, Alive); // false: dead, or no Health } ``` ```csharp /// A hit a client asked for, on one unit (entity.Run): the write is replicated with the next send. public readonly record struct TakeHit(int Damage) : IForEachEntity, INoStructuralChanges { public static int Writes => 1; public void Execute(Entity unit, ref Health hp) => hp.Value -= Damage; } ``` ### Bags, clones, leaderboards and friends `Mirror` clones a living unit with everything it has; indexes, groups and the next replication learn about the copy. `LootValue` reads a bag without counting as a write; `Give` checks with reads first, then writes both bags. `TopKillers` walks the ordered `Kills` index from the top, and `FriendsOf` asks the relation index who links to a player. ```csharp /// /// A mirror image of a living unit as it is now (health, statuses, bag, zone): a copy of the entity, which the /// indexes, groups and the next send learn about. /// public Entity Mirror(Entity unit) => unit.IsAlive ? unit.Clone() : default; /// The items in a player's bag, summed: a read, never a change. public int LootValue(Entity player) { int value = 0; foreach (var loot in player.Loot) value += loot.Item; return value; } /// A client hands a player's oldest item to another player: two tracked writes, replicated next send. public bool Give(Entity from, Entity to) { // Check with reads first: a write counts as a change, and an unchanged bag must not be replicated if (!from.HasLoot || !to.HasLoot || from.Loot.Count == 0 || to.Loot.Count == BagSize) return false; ref var source = ref from.WriteLoot(); to.WriteLoot().Add(source[0]); source.RemoveAt(0); return true; } /// The players with the most kills, best first: an ordered walk of the Kills index. public int TopKillers(Span top) { int count = 0; foreach (var player in World.KillsIndex.Descending()) { if (count == top.Length) break; top[count++] = player; } return count; } /// How many players list as a friend: the relation's index, by target. public int FriendsOf(Entity player) => World.FriendIndex.Count(player); ``` ### Leaving and changing battles A player who leaves is destroyed: its projectiles go with it (children), and the target policy removes it from every friend list. `Transfer` collects the player's whole subtree with `Descendants` and moves it to another battle of the same thread with `MoveEntities`: they arrive as new entities, the shots still its children. ```csharp /// A player leaves: its projectiles go with it (children), and it drops out of friend lists (the policy). public bool Leave(Entity player) { if (!player.IsAlive || !player.IsPlayer) return false; player.Destroy(); return true; } /// /// Move a player and its projectiles to another battle of this thread: they arrive as new entities, the shots /// still its children; links to entities left behind (friends) become null. /// public Entity Transfer(Entity player, BattleServer to) { if (!player.IsAlive || !player.IsPlayer) return default; _group.Clear(); _group.Add(player); foreach (var part in World.Descendants(player)) _group.Add(part); // the whole subtree moves together Entity arrived = default; World.MoveEntities(to.World, CollectionsMarshal.AsSpan(_group), new Span(ref arrived)); return arrived; } ``` ### A census An ad-hoc `Query` finds the nearest living player; the census adds up runners and counts. ```csharp /// The living player closest to : an ad-hoc query. public Entity NearestPlayer(Position at) { Entity nearest = default; float best = float.MaxValue; foreach (var item in World.Query(AlivePlayers)) // Position is not tracked: reads are free { float dx = item.Position.X - at.X, dy = item.Position.Y - at.Y, distance = dx * dx + dy * dy; if (distance < best) (best, nearest) = (distance, item.Entity); } return nearest; } public Census Census() { long health = 0, mana = 0; Reports.SumHealth(World, ref health); Reports.SumMana(World, ref mana); EntityId weakest = default; int lowest = int.MaxValue; Reports.FindWeakest(World, ref weakest, ref lowest); World.TryGetEntity(weakest, out var handle); // none when every player is dead return new Census(World.Count(), World.Count(AlivePlayers), health, mana, handle, World.Count(Alive)); // a frozen unit's Attack is not counted } ``` ### A new round Bulk calls change every match table by table: projectiles destroyed in one pass, statuses removed, disabled components enabled, then two parallel runners heal and scatter. ```csharp /// A new round: projectiles gone, statuses lifted, everyone healed, the NPCs scattered. public int NewRound() { int cleared = World.DestroyEntities(); // one pass, however many World.RemoveAll(); // in bulk: table by table, not per entity World.RemoveAll(); World.EnableAll(); World.EnableAll(); Reports.HealFully(World); // on all cores Reports.Scatter(World, Battle.Tick); return cleared; } ``` ### Snapshots and saves A checkpoint is an in-memory snapshot plus the change tick it was taken at, so the host can count the players written since. `Save` and `Load` write and read the whole battle as bytes; entities keep their ids, so `EntityId` links still point at the right entities. ```csharp /// Keep the battle in memory; counts the players written since. public void Checkpoint() { _checkpoint = World.Capture(); _checkpointAt = World.ChangeTick; } /// Back to the last checkpoint. public void Rewind() => World.Restore(_checkpoint); public int WrittenSinceCheckpoint => World.Count(WrittenPlayers.Since(_checkpointAt)); /// Save the battle (entities, components, singletons) as bytes: to disk, to another process. public void Save(IBufferWriter output) => World.Save(output); /// Replace the battle with a saved one: entities keep their ids, so links still point right. public void Load(ReadOnlySpan save) => World.Load(save); ``` ### Diagnostics `Describe` lists every table with its columns, rows and bytes, for a dashboard. With `MeasureSystems` on, every system's runs are timed into `system.Stats`. ```csharp /// The world's tables: their components, rows and bytes, for a dashboard. public TableInfo[] Tables() => World.Describe(); /// The system that took the most time per run so far (). public EcsSystem Slowest() { EcsSystem slowest = null; foreach (var system in World.Systems) if (slowest == null || system.Stats.Average > slowest.Stats.Average) slowest = system; return slowest; } public void Dispose() => World.Dispose(); // OnDestroy of every system ``` ## Running it ```csharp using System.Buffers; using EasyEcs.Benchmark.Showcase; using var server = new BattleServer(100_000); server.Checkpoint(); // e.g. before a risky admin command while (running) { server.Tick(); // allocates nothing once the tables reach their peak if (server.WrittenSinceCheckpoint > 1_000) server.Checkpoint(); } var census = server.Census(); // between ticks: runners, Count, groups Console.WriteLine($"{census.Alive}/{census.Players} alive, {server.PlayersIn(0)} in zone 0, slowest {server.Slowest()}"); server.Ceasefire = true; // a rule as data: players hold fire, shots in flight expire server.NewRound(); server.Rewind(); // roll the battle back in memory var save = new ArrayBufferWriter(); server.Save(save); // to disk, or to another process: Load(save.WrittenSpan) using var other = new BattleServer(10_000); server.Transfer(server.NearestPlayer(default), other); // a player and its projectiles change battles // One world per thread scales across cores: worlds share nothing. var threads = new Thread[4]; for (int i = 0; i < threads.Length; i++) (threads[i] = new Thread(() => { using var battle = new BattleServer(25_000); while (running) battle.Tick(); })).Start(); ``` Every system can be removed, reordered or tested alone: they share components and singletons, nothing else. ## What a tick costs `BattleServerBenchmark` ticks a battle of 100,000 units 1,200 times to bring every table to its peak population, then measures one tick: every system above, with replication every third tick. | Case | Mean | vs baseline | Allocated | | ---- | ------- | ----------- | --------- | | Tick | 2.97 ms | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The other benchmarks, and how to run them: [Performance](https://ecs.xgamedev.net/en/docs/performance). ## More programs - [`samples/`](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples): complete programs in learning order: hello world, a fixed-tick game loop fed by a network thread, saves and moves between worlds, one world per thread, hot-reloaded game logic. - The guide: the pages of single features have a full example of that feature alone, for instance [change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking#full-example). - [`templates/`](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/templates): `dotnet new` templates for a new project. ## Related - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): Build a smaller simulation step by step. - [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles): Why every system here has one job and talks to others only through data. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): The replication above: what counts as a write, ticks, removals. - [Performance](https://ecs.xgamedev.net/en/docs/performance): Which API to use when, and every benchmark. --- # Structuring a real project > Lay out an EasyEcs server the way dotnet new easyecs does: Components/, one system per file, Program.cs as the host, groups for cadence, input, tests and saves. URL: https://ecs.xgamedev.net/en/docs/guide/project-structure Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/project-structure.md A server outgrows one file fast. This page lays out an EasyEcs project the way the `dotnet new easyecs` template does and says where each part goes: data in `Components/`, rules in `Systems/`, the loop in `Program.cs`, one test file per system. Each part has one job, so a new feature is a new component and a new system, never an edit to the loop. ## When to use it > **Use it for** > > Any server or tool that will grow past the [getting started](https://ecs.xgamedev.net/en/docs/getting-started) program: a game server, a > simulation, a bot farm. The layout also fits a world hosted in ASP.NET Core or a Worker Service; only the host > changes ([hosting](https://ecs.xgamedev.net/en/docs/guide/hosting)). > **Skip it for** > > A one-file experiment or a benchmark: there, folders add nothing. Splitting one world's logic over several > assemblies is not needed either, unless you reload part of it at runtime (see > [persistence and hot reload](https://ecs.xgamedev.net/en/docs/guide/project-structure#persistence-and-hot-reload)). ## How to use it ### Start from the template's project structure `EasyEcs.Templates` creates a console server that updates a world 20 times a second until Ctrl+C. `--tests` adds an NUnit project with one test file per system. ```bash dotnet new install EasyEcs.Templates dotnet new easyecs -n MyServer --tests cd MyServer dotnet run -- --ticks 100 ``` - MyServer/ - MyServer.csproj - Program.cs - Components/ - Movement.cs - Lifetime.cs - Clock.cs - Spawner.cs - Systems/ - SpawnSystem.cs - MovementSystem.cs - LifetimeSystem.cs - ClockSystem.cs - MyServer.Tests/ - MyServer.Tests.csproj - SpawnSystemTests.cs - MovementSystemTests.cs - LifetimeSystemTests.cs - ClockSystemTests.cs The package carries the generator and the analyzer, so `MyServer.csproj` holds one `PackageReference` and nothing to configure. ### Put data in `Components/` One file per thing the data describes, holding its components: `Movement.cs` has `Position` and `Velocity`, `Lifetime.cs` has `Lifetime`. Singletons go there too, one file each. Components are plain data: no methods, no references to services, and small enough that a system reads only what it needs ([ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles)). ```csharp // How many ticks an entity has left. LifetimeSystem destroys it when they run out. public record struct Lifetime(int Ticks) : IComponent; ``` ### One system per file, one job per system Each file in `Systems/` holds one system with one responsibility, named after it: `MovementSystem` moves, `LifetimeSystem` expires. The game's rules all live here, even "spawn a wave every second", so they run in the order you choose and can be tested one by one. Add a system with the item template: ```bash dotnet new easyecs-system -n RegenSystem -o Systems ``` Systems keep no state of their own ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007)) and never call each other ([EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008)): what one system leaves for another is a component or a singleton. See [Systems and `[ForEach]`](https://ecs.xgamedev.net/en/docs/guide/systems). ### `Program.cs` is only the host `Program.cs` builds the world, sets the singletons, adds the systems and runs the loop. It holds no game rule: when you are about to write an `if` about the game there, write a system instead. Set every singleton before the first update. A system that reads a missing singleton throws on its first run, naming it and the call that adds it ([D27](https://ecs.xgamedev.net/en/docs/decisions#d27-reading-a-missing-singleton-throws-everywhere)): ```text Singleton Spawner was not added to this world: set it before the systems that read it run (world.SetSpawner(...) or world.AddSingleton()), or use GetOrAddSpawner() where a default is meant ``` Where the default value is right, such as a counter that starts at zero, `GetOrAddX()` says so in the code that reads it. Singletons that come from a save are not set again after `Load` ([load at start, save at stop](https://ecs.xgamedev.net/en/docs/guide/hosting#persistence)). ### Keep the order in one place Systems run in the order they are added. Put the `AddSystem` calls in one method that `Program.cs` and the tests both call, so a test of the whole tick runs the tick the server runs ([share the setup](https://ecs.xgamedev.net/en/docs/guide/testing#share-the-setup)): ```csharp public static class Game { public static void AddSystems(World world) { world.AddSystem(); world.AddSystem(); } } public record struct Ttl(int Ticks) : IComponent; public class MoveSystem : EcsSystem { [ForEach] static void Move(ref Position position, in Velocity velocity) => position = new Position(position.X + velocity.X, position.Y + velocity.Y); } public class ExpireSystem : EcsSystem { [ForEach] static void Expire(Entity entity, ref Ttl ttl) { if (--ttl.Ticks <= 0) entity.Destroy(); } } ``` ### Give each cadence a group Not everything runs every tick. A system group is a cadence the host calls: systems marked `[UpdateInGroup]` run on `world.Update()`, the others on `world.Update()`. Use one group for input read whenever it arrives, one for replication every few ticks, one for autosaves. Inside a group, `UpdateInterval` runs a slow system every N-th update and `UpdatePhase` spreads systems with the same interval ([`UpdateInterval` and `UpdatePhase`](https://ecs.xgamedev.net/en/docs/guide/systems#update-interval)): ```csharp public record struct Census(int Entities) : ISingletonComponent; // Every 20th update of its group: once a second at 20 ticks a second. public class CensusSystem : EcsSystem { public override int UpdateInterval => 20; protected override void OnUpdate() => World.GetOrAddCensus().Entities = World.EntityCount; } ``` One tick of the [full example](https://ecs.xgamedev.net/en/docs/guide/project-structure#full-example), as the host runs it: ```mermaid flowchart LR W["host wakes up"] --> I["Update<InputGroup>()
inbox → FireRequest"] I --> U["Update()
Fire, Spawn, Movement,
Lifetime, Clock"] U --> S["sleep until
the next tick"] S --> W ``` ### Take input through a mailbox The network, timers and the database run on other threads; the world belongs to the one thread that updates it. They meet in a queue you own: other threads post messages, and a system on the world's thread takes them and turns each into data. The queue is a `readonly` field of that system, handed in when it is added: a dependency, not state, so [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007) allows it. Not a singleton: `World.Save` writes every singleton, and a queue has no formatter. ```csharp using System.Collections.Concurrent; public readonly record struct FireCommand(float Vx, float Vy); // a message, not a component public record struct FireRequest(float Vx, float Vy) : IComponent; public struct InputGroup : ISystemGroup; [UpdateInGroup] public class ReceiveCommandsSystem(ConcurrentQueue inbox) : EcsSystem { private readonly ConcurrentQueue _inbox = inbox; // filled by the network threads protected override void OnUpdate() { while (_inbox.TryDequeue(out var command)) World.CreateEntity(new FireRequest(command.Vx, command.Vy)); } } ``` Add it with `world.AddSystem(new ReceiveCommandsSystem(inbox))`, and give the same queue to the network code. The queue's bound and what happens when it is full are yours to choose. The details are in [input from other threads](https://ecs.xgamedev.net/en/docs/guide/threading#input-from-other-threads); a server that answers requests is in [hosting](https://ecs.xgamedev.net/en/docs/guide/hosting#requests). ### One test file per system `MyServer.Tests` has a test file per system: a world of its own with the singletons and entities the system needs, one update, assertions on the data it left. Add a test of the whole tick through `Game.AddSystems`. The template's `MyServer.csproj` leaves the test folder out of the server's build (``). See [Testing systems](https://ecs.xgamedev.net/en/docs/guide/testing). ### Look inside when something is off `WorldOptions.MeasureSystems` times every system, `SystemErrors = SystemErrorPolicy.Disable` turns a failing system off instead of stopping the tick, and `world.Describe()` shows the tables. Add them to the host's options when you need them; see [Debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics). ### Persistence and hot reload - **Saves:** load the last save before the first tick and save after the loop ends, from the host ([saves](https://ecs.xgamedev.net/en/docs/guide/saves), [load at start, save at stop](https://ecs.xgamedev.net/en/docs/guide/hosting#persistence)). The [SaveLoad sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/SaveLoad) saves a world, a group of entities, and moves entities between worlds. - **Hot reload:** to replace game logic while the world runs, move those systems and components into a plugin assembly and load it into a collectible context ([migration and unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload)). The [HotReload sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/HotReload) splits the project into contracts, plugin and host. ## Full example The template's server with the two parts a real one adds: commands from a network thread, read through a mailbox in an input group, and the system order in `Game.cs`, shared with the tests. Create it with `dotnet new easyecs -n MyServer --tests`, add the new files, and run it with `dotnet run -- --ticks 60`. **Components/Movement.cs** ```csharp using EasyEcs; namespace MyServer; // Components are plain data on entities: fields, no logic. Keep them small. A field that // a system does not read every tick belongs in a component of its own. public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; ``` **Components/Lifetime.cs** ```csharp using EasyEcs; namespace MyServer; // How many ticks an entity has left. LifetimeSystem destroys it when they run out. public record struct Lifetime(int Ticks) : IComponent; ``` **Components/Clock.cs** ```csharp using EasyEcs; namespace MyServer; // A singleton: one value per world instead of one per entity. // Tick counts the updates; DeltaTime is the length of one tick in seconds. public record struct Clock(long Tick, float DeltaTime) : ISingletonComponent; ``` **Components/Spawner.cs** ```csharp using EasyEcs; namespace MyServer; // What SpawnSystem creates, and how often. Bullet is a prefab: a recipe of component values // that every spawned entity starts from. A wave of Wave bullets appears every Interval ticks. public record struct Spawner(Prefab Bullet, int Wave, int Interval) : ISingletonComponent; ``` **Components/Input.cs (new)** ```csharp using EasyEcs; namespace MyServer; // What a client sends. A message, not a component: ReceiveCommandsSystem turns it into data. public readonly record struct FireCommand(float Vx, float Vy); // A command as data: FireSystem handles it on the next tick, then destroys it. public record struct FireRequest(float Vx, float Vy) : IComponent; ``` **Systems/InputGroup.cs (new)** ```csharp using EasyEcs; namespace MyServer; // A cadence of its own: the host runs world.Update() whenever it wants input read, // independently of the simulation tick that world.Update() runs. public struct InputGroup : ISystemGroup; ``` **Systems/ReceiveCommandsSystem.cs (new)** ```csharp using System.Collections.Concurrent; using EasyEcs; namespace MyServer; // Turns every command waiting in the inbox into a FireRequest entity. // It runs on the world's thread, so creating entities here is safe; the network // threads only ever touch the queue. [UpdateInGroup] public class ReceiveCommandsSystem(ConcurrentQueue inbox) : EcsSystem { // The mailbox from the network threads. A readonly field is a dependency, not state // (EECS007 allows it); a singleton would not do, since World.Save writes every singleton. private readonly ConcurrentQueue _inbox = inbox; protected override void OnUpdate() { while (_inbox.TryDequeue(out var command)) { World.CreateEntity(new FireRequest(command.Vx, command.Vy)); } } } ``` **Systems/FireSystem.cs (new)** ```csharp using EasyEcs; namespace MyServer; // Fires one bullet per request, from the spawner's prefab, then destroys the request. // Creating and destroying entities in the middle of the pass is safe. public class FireSystem : EcsSystem { [ForEach] static void Fire(World world, Entity request, in FireRequest fire, in Spawner spawner) { Entity bullet = world.Instantiate(spawner.Bullet); bullet.SetVelocity(fire.Vx, fire.Vy); request.Destroy(); } } ``` **Systems/SpawnSystem.cs** ```csharp using EasyEcs; namespace MyServer; // Spawns a wave of bullets from the spawner's prefab every Interval ticks. // The game's rules live in systems like this one, never in Program.cs. public class SpawnSystem : EcsSystem { protected override void OnUpdate() { ref readonly var spawner = ref World.Spawner; bool waveDue = World.Clock.Tick % spawner.Interval == 0; if (!waveDue) { return; } for (int i = 0; i < spawner.Wave; i++) { World.Instantiate(spawner.Bullet); } } } ``` **Systems/MovementSystem.cs** ```csharp using EasyEcs; namespace MyServer; // Moves every entity with a position and a velocity over one tick. // A [ForEach] method runs once per entity that has all of its component parameters: // `ref` for what it writes, `in` for what it reads. A singleton can be a parameter too. public class MovementSystem : EcsSystem { [ForEach] static void Move(ref Position position, in Velocity velocity, in Clock clock) { float dt = clock.DeltaTime; position = new Position(position.X + velocity.X * dt, position.Y + velocity.Y * dt); } } ``` **Systems/LifetimeSystem.cs** ```csharp using EasyEcs; namespace MyServer; // Counts down every lifetime and destroys the entity when it runs out. // Destroying an entity in the middle of the pass is safe. public class LifetimeSystem : EcsSystem { [ForEach] static void Age(Entity entity, ref Lifetime lifetime) { lifetime.Ticks--; if (lifetime.Ticks <= 0) { entity.Destroy(); } } } ``` **Systems/ClockSystem.cs** ```csharp using EasyEcs; namespace MyServer; // Advances the clock once per update. OnUpdate runs once per update, not once per entity. // Game.AddSystems adds it last, so every other system sees the tick the update started with. public class ClockSystem : EcsSystem { protected override void OnUpdate() { World.Clock.Tick++; } } ``` **Game.cs (new)** ```csharp using System.Collections.Concurrent; using EasyEcs; namespace MyServer; // The server's systems, in the order they run. Program.cs and the tests both call it, // so a test of the whole tick runs the tick the server runs. public static class Game { public static void AddSystems(World world, ConcurrentQueue inbox) { // Input group: runs on world.Update(), when the host reads input. world.AddSystem(new ReceiveCommandsSystem(inbox)); // Default group: the simulation, once per world.Update(), in this order. world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); } } ``` **Host/FakeClient.cs (new)** ```csharp using System.Collections.Concurrent; namespace MyServer.Host; // Plumbing, not ECS: stands in for the network. A thread of its own posts five fire // commands, 100 ms apart, into the inbox. It never touches the world. public static class FakeClient { public static Thread Start(ConcurrentQueue inbox) { var thread = new Thread(() => { for (int i = 0; i < 5; i++) { Thread.Sleep(100); inbox.Enqueue(new FireCommand(Vx: 0, Vy: 20)); } }); thread.IsBackground = true; thread.Start(); return thread; } } ``` **Program.cs** ```csharp using System.Collections.Concurrent; using System.Diagnostics; using EasyEcs; using MyServer; using MyServer.Host; // The host: it builds the world, then updates it on a fixed tick until Ctrl+C // (or `--ticks N`). The game itself is in Components/ and Systems/. const int TicksPerSecond = 20; long ticksToRun = long.MaxValue; if (args.Length == 2 && args[0] == "--ticks") { ticksToRun = long.Parse(args[1]); } // Ctrl+C stops the loop cleanly instead of killing the process. using var stop = new CancellationTokenSource(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.Cancel(); }; using var world = new World(); // Singletons first: the systems read them, and a missing one throws on the first update. var inbox = new ConcurrentQueue(); world.SetClock(Tick: 0, DeltaTime: 1f / TicksPerSecond); world.SetSpawner( Bullet: new Prefab().SetPosition(0, 0).SetVelocity(10, 0).SetLifetime(3 * TicksPerSecond), Wave: 100, Interval: TicksPerSecond); Game.AddSystems(world, inbox); // The network: another thread, which only posts to the inbox. FakeClient.Start(inbox); var tickLength = TimeSpan.FromSeconds(1.0 / TicksPerSecond); var clock = Stopwatch.StartNew(); var nextTick = TimeSpan.Zero; while (world.Clock.Tick < ticksToRun && !stop.IsCancellationRequested) { // Read the input that arrived, then run one tick of the simulation. world.Update(); world.Update(); long tick = world.Clock.Tick; if (tick % TicksPerSecond == 0) { Console.WriteLine($"tick {tick}: {world.EntityCount} entities"); } // Sleep until the next tick is due. nextTick += tickLength; TimeSpan wait = nextTick - clock.Elapsed; if (wait > TimeSpan.Zero) { stop.Token.WaitHandle.WaitOne(wait); } } Console.WriteLine($"stopped after {world.Clock.Tick} ticks"); ``` **MyServer.Tests/TickTests.cs (new)** ```csharp using System.Collections.Concurrent; using EasyEcs; using NUnit.Framework; namespace MyServer.Tests; // The whole tick, through the same Game.AddSystems the server calls. public class TickTests { [Test] public void AQueuedCommandBecomesABulletOnTheNextTick() { using var world = new World(); var inbox = new ConcurrentQueue(); // Tick 1: no wave is due, so the only bullet is the one fired. world.SetClock(Tick: 1, DeltaTime: 0.05f); world.SetSpawner( Bullet: new Prefab().SetPosition(0, 0).SetVelocity(0, 0).SetLifetime(10), Wave: 100, Interval: 20); Game.AddSystems(world, inbox); inbox.Enqueue(new FireCommand(Vx: 0, Vy: 20)); world.Update(); world.Update(); Assert.That(world.Count(), Is.EqualTo(1)); Assert.That(world.Count(), Is.Zero); } } ``` It prints: ```text tick 20: 105 entities tick 40: 205 entities tick 60: 205 entities stopped after 60 ticks ``` The five commands arrive during the first half second and become five bullets next to the first wave of 100. At tick 60 the first wave has run out of time while the third one appears; the fired bullets, a few ticks younger, are still alive. No line of `Program.cs` knows about bullets: the host only sets data, adds systems and keeps time. ## How to use it fast The layout itself has no cost to tune: folders and files are gone once the project compiles. What decides the speed of the tick is in the systems: `in` for what a method only reads, a group or `UpdateInterval` for what does not run every tick, and the choices the [performance guide](https://ecs.xgamedev.net/en/docs/performance) measures. ## What it costs Nothing at run time: one system per file compiles to the same code as one file of systems, and a group is a call the host makes. The tick costs what its systems cost; [performance](https://ecs.xgamedev.net/en/docs/performance) has the numbers per feature. ## Pitfalls | Mistake | What happens | Caught by | | ------------------------------------------------------------------ | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | A game rule in `Program.cs` (a wave every second, a win condition) | It cannot be tested alone or ordered against the systems | Review: move it into a system that reads a singleton | | Program and tests adding the systems in different orders | The tests pass on a tick the server never runs | Share one `Game.AddSystems` | | A singleton set after the first update, or never | The first system that reads it throws `InvalidOperationException` naming it | The runtime, on the first update | | A system keeping a counter or a timer in a field | State no save, snapshot or test sees | [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007) | | The network thread creating entities itself | An exception from the structural gate, or torn tables when it misses the race | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) when it can see it; post to the mailbox | | The test folder inside the server project | NUnit types compiled into the server | `` (the template has it) | ## Related - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): The concepts this layout organizes, one step at a time. - [Testing systems](https://ecs.xgamedev.net/en/docs/guide/testing): A world per test, shared setup, errors and allocation budgets. - [Hosting in a .NET server](https://ecs.xgamedev.net/en/docs/guide/hosting): The same world inside ASP.NET Core or a Worker Service. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): The owner thread, input from other threads and parallel systems. --- # Entities and components > How EasyEcs stores game objects as entities with struct components. Version-checked handles, EntityId references, tags, Set/Get/Read and generated members. URL: https://ecs.xgamedev.net/en/docs/guide/entities-and-components Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/entities-and-components.md Every object of a server is an entity: a player, an NPC, a projectile, a loot chest. An entity is only an identity; its data lives in components, plain structs stored in tables with one row per entity. A handle to an entity checks its version on every access, so a player who logged out, or a monster that died and whose id went to a new monster, can never be written through an old handle. ## When to use it > **Use it for** > > Everything that exists many times and changes over time: units, items, sessions, timers. Put each piece of data in > its own small component (`Position`, `Health`) and each state in a tag (`Dead`, `Stunned`), so systems select > exactly the entities they work on. > **Skip it for** > > Data of the whole world (a clock, configuration, a spatial grid): that is a [singleton](https://ecs.xgamedev.net/en/docs/guide/singletons). > Behavior inside components: components are data, logic goes into [systems](https://ecs.xgamedev.net/en/docs/guide/systems). Classes as > components: they do not compile ([EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006)). ## How to use it ### Declare components A component is a struct that implements `IComponent`. A `record struct` gives you a constructor, equality and `ToString` for free. A struct without fields is a tag. ```csharp public record struct Position(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent; public record struct Armor(int Value) : IComponent, ITrackChanges; // writes are tracked public record struct Name(string Value) : IComponent; // managed fields are allowed public struct Dead : IComponent; // a tag: no fields ``` ### Create entities `CreateEntity` takes 0 to 9 component values and places the entity in its final table in one step. ```csharp var world = new World(); Entity goblin = world.CreateEntity(new Position(10, 0), new Health(30), new Armor(2)); Entity marker = world.CreateEntity(); // no components yet ``` ### Read, write, add and remove The generator gives every component named members, so the common calls read like fields. Write through a `ref`, add or replace with `SetX`, remove with `RemoveX`. ```csharp goblin.Position.X += 1; // a ref into the table: written in place goblin.SetHealth(25); // adds or replaces the value int armor = goblin.Armor.Value; // a tracked component: ref readonly, a read is not a write goblin.SetDead(); // adds the tag if (goblin.IsDead) goblin.RemoveHealth(); // removes a component; the entity keeps its row goblin.Destroy(); ``` ### Entities An `Entity` is a 16-byte handle: the world, and an [`EntityId`](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#entityid) (index and version). It holds no data and no behavior. Every member validates the version first: | Call on a destroyed or `default` handle | Result | | ------------------------------------------------------------------------------ | -------------------------------------------------- | | `IsAlive`, `Has()`, `TryGet()`, `TryGetRef()` | `false` (no exception) | | `Get()`, `Read()`, `GetOrAdd()`, `Set(...)`, `Remove()`, `Clone()` | `InvalidOperationException`: "Entity is not alive" | | `Destroy()` | ignored | Two handles are equal when they name the same incarnation in the same world. Destroying an entity bumps its version, so every handle to it becomes stale at once, and it never reaches the entity that later reuses the index. Waves of spawns and clean-ups have bulk forms, each one pass through the structural gate: ```csharp var wave = new Entity[500]; world.CreateEntities(wave, new Position(0, 0), new Health(100)); // the same values for each; handles written to wave int cleared = world.DestroyEntities(); // every dead entity with Health ``` Kinds of entities spawned again and again (an NPC type, a projectile) are best defined once as a [prefab](https://ecs.xgamedev.net/en/docs/guide/prefabs): `world.Instantiate(prefab)` creates one, `entity.Clone()` copies a living one. The world counts and lists its entities: ```csharp world.EnsureEntityCapacity(10_000); // a server that knows its peak never grows the entity records int alive = world.EntityCount; // O(1) foreach (var e in world.Entities) // diagnostics: walks the whole id range Console.WriteLine(e); ``` `WorldOptions.InitialEntityCapacity` does the same at construction: ```csharp var sized = new World(new WorldOptions { InitialEntityCapacity = 10_000 }); ``` Tables grow on their own; to size a table too, use [`EnsureCapacity(count)`](https://ecs.xgamedev.net/en/docs/guide/structural-changes#bulk) for entities created with exactly those components, or [`EnsureCapacity(prefab, count)`](https://ecs.xgamedev.net/en/docs/guide/prefabs#ensure-capacity) for a prefab's instances. ### Ids, versions and recycling `entity.Id` is an `EntityId`: 8 bytes, an `Index` and a `Version`, unmanaged. It is what you store in a component, send to a client or write to a log. `world.TryGetEntity(id, out var e)` turns it back into a handle when that incarnation is still alive, and a handle converts to its id implicitly. ```csharp var target = world.CreateEntity(new Health(100)); EntityId fromClient = target.Id; // what a client sends back if (world.TryGetEntity(fromClient, out var found) && found.HasHealth) found.Health.Value -= 10; // the current incarnation of that id target.Destroy(); bool gone = !world.IsAlive(fromClient); // true: the id names the destroyed incarnation var reused = world.CreateEntity(); // may take the same index, with a new version bool same = reused.Id == fromClient; // false ``` - **Indexes are recycled** last in, first out, so recently freed slots are still warm in cache and the entity records stay bounded by the peak population. - **Versions start at 1.** `EntityId.Null` (`default`) has version 0 and names no entity; `id.IsNull` tests it. - `world.GetEntity(id)` throws instead of returning false. #### Refer to entities with `EntityId` A component that points at another entity (an owner, a target, a parent) stores the `EntityId`, not the `Entity`. An `Entity` holds a reference to its world, so a component with an `Entity` field becomes a managed column: the GC scans it, every store pays a write barrier, rows are no longer copied as blocks and saves cannot write it. The analyzer warns ([EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017)). ```csharp public record struct Target(EntityId Id) : IComponent; // 8 bytes, unmanaged public class Chase : EcsSystem { [ForEach] static void Follow(ref Position p, in Target target, World world) { if (world.TryGetEntity(target.Id, out var prey)) p = prey.Position; // gone: the id finds nothing } } ``` To find every entity that points at a target, make the link an indexed component or a relation: [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations). ### Components The generic API works for any component type; the [generated members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members) are shorthands for it. | Operation | Effect | | ------------------------------------ | ------------------------------------------------------------------------------------- | | `ref T Get()` | A ref into the table; throws if the entity lacks `T`. A write of a tracked component. | | `ref readonly T Read()` | A read-only ref; throws if missing. Never a write. | | `ref T TryGetRef(out bool found)` | A ref if present, else a null ref (check `found`). A write when found. | | `bool TryGet(out T value)` | A **copy** if present. Never a write. | | `bool Has()` | Whether the entity has all of them. | | `Entity Set(in T1 … in Tn)` | Adds or replaces 1 to 9 values, with at most one row move; chainable. | | `ref T GetOrAdd()` | A ref, adding `default` first if missing; an existing value is kept. | | `Entity Remove()` | Removes 1 to 9 components; missing ones are ignored; chainable. | ```csharp var hero = world.CreateEntity(new Position(0, 0), new Health(100), new Name("Ayla")); hero.Set(new Armor(3), new Position(5, 5)); // one call: shorter than two, same cost ref var hp = ref hero.TryGetRef(out bool has); if (has) hp.Value -= 10; // one lookup, written in place ref var shield = ref hero.GetOrAdd(); // kept: Armor(3) hero.Remove(); bool both = hero.Has(); ``` Always change components through a `ref`: `var hp = hero.Get()` is a copy, and changing it changes nothing in the table ([`ref` and `await`](https://ecs.xgamedev.net/en/docs/guide/refs-and-await)). ### Generated members The source generator gives `Entity`, `World` and `Prefab` named members for every component and singleton of your project (C# 14 extension members, the .NET 10 default). Each one is an inlined call to the generic API, so both cost the same. | Declared | Generated | Same as | | ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `record struct Position(float X, float Y) : IComponent` | `e.Position` (`ref`), `e.HasPosition`, `e.TryGetPosition(out p)`, `e.GetOrAddPosition()`, `e.SetPosition(x, y)`, `e.RemovePosition()` | `Get`, `Has`, `TryGet`, `GetOrAdd`, `Set(new Position(x, y))`, `Remove` | | a tracked component (`Armor : ITrackChanges`) | `e.Armor` is `ref readonly`; `e.WriteArmor()` returns the `ref` | `Read`; `Get` (stamped as written) | | an indexed component (`Zone : IIndexed`) | `e.Zone` is `ref readonly`, no `GetOrAddZone` or `WriteZone`; `world.ZoneIndex` | `Read`; `world.Index()` | | a grouped component (`Team : IGroup`) | `e.Team` is `ref readonly`, no `GetOrAddTeam` or `WriteTeam`; `filter.InTeam(group)` | `Read`; `filter.InGroup(group)` ([groups](https://ecs.xgamedev.net/en/docs/guide/groups)) | | a tag (`struct Dead : IComponent`) | `e.IsDead`, `e.SetDead()`, `e.RemoveDead()` | `Has`, `Set(new Dead())`, `Remove` | | any component with fields, except a cleanup component | `e.DisableHealth()`, `e.EnableHealth()`, `e.IsHealthDisabled` | [`Disable` / `Enable`](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) | | a buffer element some code names as `DynamicBuffer` | `e.Loot` (`ref readonly`), `e.HasLoot`, `e.WriteLoot()`, `e.GetOrAddLoot()`, `e.RemoveLoot()` | `Read`, `Has`, `Get`, `GetOrAdd`, `Remove` of `DynamicBuffer` ([dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers)) | | a relation (`MemberOf : IRelation`), once code names `DynamicBuffer` | `e.AddMemberOf(target)`, `e.RemoveMemberOf(target)`, `e.LinksMemberOf(target)`, `e.MemberOf` (`ref readonly`), `e.HasMemberOf`, `e.RemoveMemberOf()`, `world.MemberOfIndex` | `AddRelation`, `RemoveRelation`, `HasRelation`, `Read`, `Has`, `Remove`, `world.Relations()` ([relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#relations)) | | a singleton (`Clock : ISingletonComponent`) | `world.Clock` (`ref`), `world.HasClock`, `world.GetOrAddClock()`, `world.SetClock(…)`, `world.RemoveClock()` | [`GetSingleton`](https://ecs.xgamedev.net/en/docs/guide/singletons), `HasSingleton`, `GetOrAddSingleton`, `GetOrAddSingleton() = …`, `RemoveSingleton` | | each `world.Query()` the code calls | `item.Position`, `item.Velocity` | `item.Component1`, `item.Component2` | | any component, on a [prefab](https://ecs.xgamedev.net/en/docs/guide/prefabs#generated-members) | `prefab.Position` (`ref readonly`), `HasPosition`, `SetPosition(x, y)`, `RemovePosition()`, `IsDead`, `SetDead()` | `Read`, `Has`, `Set`, `Remove` | ```csharp hero.Position.X += 1; // ref: written in place if (hero.TryGetHealth(out var copy)) Console.WriteLine(copy.Value); hero.SetArmor(5).SetDead(); // constructor arguments; a tag; chainable int value = hero.Armor.Value; // tracked: a read, never stamped hero.WriteArmor().Value += 1; // an explicit write: stamped ``` - The property is `Get` (or `Read`), so it throws when the component is missing: check `HasX`, or use `TryGetX` / `TryGetRef(out found)` when it is optional. - `SetX` has one overload per public constructor (a record struct's primary constructor), or one that takes every field when the struct has no constructor and only public, writable fields. - Writes are methods, not property setters: C# rejects a setter on a handle that is not a variable, such as a `foreach` variable. - The analyzer knows these members: `SetX`, `GetOrAddX` and `RemoveX` are structural changes, the rest are reads or writes of a value. - No members are generated for generic components, components nested in types other code cannot see, and names the receiver already has (`Entity.Id`, `World.Update`); the generic API still works for them. ### Tags A tag is a component without fields: `public struct Dead : IComponent;`. It costs no column and exists to be filtered on (`[Without]`, `QueryFilter.Create().With()`). Use tags for states that come and go (dead, stunned, burning). Removing a tag and adding it back flips one presence bit in the entity's row, so a state that toggles every few ticks moves no data. For a value that changes every tick, a field is still cheaper: [ECS principles, rule 5](https://ecs.xgamedev.net/en/docs/ecs-principles#5-choose-the-cheapest-representation-for-frequent-changes). ### Where components live Components live in archetype tables, one row per entity and one column per component type. - **Removing a component keeps the row.** The column's presence bit for that row is cleared; adding the component back sets it again. Nothing moves. - **Gaining a component the table has no column for moves the row** to the table with that column, once per new combination. The move plan is cached per source table. - **Managed values are cleared on removal** (and when the entity is destroyed), so the GC can collect what they referenced. Unmanaged values are left in place: the next `Set` or `GetOrAdd` overwrites them. - Up to 65,536 component types per process. The first 256 fit in each table's mask inline; past that, a mask carries an overflow array. ## Full example A goblin and a chest: create them, write through the generated members, mark a state with a tag, read an optional component, then destroy the goblin and check its id. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent; // Tracked: the generated property is read-only, and a write is explicit. public record struct Armor(int Value) : IComponent, ITrackChanges; // A tag: no fields, only filtered on. public struct Dead : IComponent; ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); // Each entity is placed in its final table in one step. var goblin = world.CreateEntity(new Position(0, 0), new Health(30), new Armor(2)); var chest = world.CreateEntity(new Position(5, 5)); // Generated members: a ref to write in place, SetX to add or replace, WriteX for a tracked write. goblin.Position.X += 3; goblin.SetHealth(goblin.Health.Value - 40); goblin.WriteArmor().Value += 1; // goblin.Armor is Read(): a tracked component read without counting as a write. Console.WriteLine($"goblin: {goblin.Position}, {goblin.Health}, armor {goblin.Armor.Value}"); // A tag is a state: set it, test it. if (goblin.Health.Value <= 0) { goblin.SetDead(); } Console.WriteLine($"goblin dead: {goblin.IsDead}, chest dead: {chest.IsDead}"); // An optional component: TryGetX copies the value when the entity has it. if (chest.TryGetHealth(out var chestHealth)) { Console.WriteLine($"chest: {chestHealth}"); } else { Console.WriteLine("chest: no health, nothing to hit"); } // The id outlives the entity: after Destroy it names nothing. EntityId id = goblin.Id; goblin.Destroy(); Console.WriteLine($"{id} alive: {world.IsAlive(id)}, entities left: {world.EntityCount}"); ``` It prints: ```text goblin: Position { X = 3, Y = 0 }, Health { Value = -10 }, armor 3 goblin dead: True, chest dead: False chest: no health, nothing to hit 0v1 alive: False, entities left: 1 ``` `goblin.Position.X += 3` wrote the table in place, while the chest, which has no `Health`, answered `TryGetHealth` with `false` instead of throwing. After `Destroy` the stored id names nothing: the world says it is not alive. ## How to use it fast | Instead of | Do | Why | | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | `CreateEntity()` then `Set` per component | `CreateEntity(a, b, c)`, or `Instantiate(prefab)` | One placement instead of one row move per component | | `Set(a)` then `Set(b)` | `Set(a, b)`, `Remove()` | Shorter, the same cost | | A loop of `CreateEntity` / `Destroy` | `CreateEntities(span, …)`, `DestroyEntities(filter)` ([EECS031](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs031)) | One pass through the structural gate per wave | | `Get()` to read a tracked component | `Read()`, the generated property, `TryGet()` | A `ref` access stamps the row as written | | `Has()` then `Get()` | `TryGetRef(out found)` | One lookup | | Several `Get` / `TryGetRef` and a `Has()` per request | [`entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity) with a `static readonly` filter | One lookup for every component; the refs survive structural changes | | An `Entity` field in a component | An `EntityId` field | Unmanaged column: no GC scan, block copies | Per-entity access through handles, 1,000 handles each (`MicroBenchmarks`: `HandleAccess` writes `Position` through the handle, `TryGetEntity` looks the id up first, `TrackedHandleWrite` writes a tracked component): | Case | Mean | vs baseline | Allocated | | ------------------ | ------- | ----------- | --------- | | HandleAccess | 3.33 μs | 0.26× | 0 B | | TryGetEntity | 3.60 μs | 0.28× | 0 B | | TrackedHandleWrite | 8.37 μs | 0.66× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Creating and destroying in a warm world, 1,000 entities ten times over: one call per entity (`Churn`) against `CreateEntities` and `DestroyEntities` (`ChurnBatch`); and moving three components out and back in one call each (`RemoveMany`, 1,000 entities): | Case | Mean | vs baseline | Allocated | | ---------- | ------- | ----------- | --------- | | Churn | 334 μs | 26× | 0 B | | ChurnBatch | 157 μs | 12× | 0 B | | RemoveMany | 51.0 μs | 4.0× | 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 mixed world: spawning and destroying 5,000 projectiles, and stunning 5% of the fighters then lifting it (two structural changes each): **Structural changes per operation, 100,000 entities** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------- | ------- | ---------- | --------- | | EasyEcs | CreateDestroy | 190 μs | 1.00× | 0 B | | Friflo.Engine.ECS | CreateDestroy | 215 μs | 1.13× | 0 B | | EasyEcs | Toggle | 517 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Toggle | 1.00 ms | 1.94× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Per entity:** a 16-byte record (table, row, version) outside the tables, plus its row. - **A handle** is 16 bytes; an `EntityId` 8 bytes. - **`Get`, `Read`, `Has` through a handle:** the entity's record, then one cache line of the table's lookup. O(1). - **Create:** O(components), amortized; a new combination of components creates its table once. - **Destroy:** O(components); outside a pass the table's last row fills the hole at once. - **Remove a component, add it back:** one presence bit. Gaining a new column: one row copy. - **Writes of untracked components** cost nothing extra; tracked ones store one tick ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking#what-it-costs)). - After warm-up, none of this allocates. ## Pitfalls | Mistake | What happens | Caught by | | -------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | A class implementing `IComponent` | Does not compile | [EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006) | | An `Entity` field in a component | A managed column, scanned by the GC, not saved | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) (warning) | | Changing a copy: `var hp = e.Get(); hp.Value--;` | The table is unchanged | Code review: `ref var hp = ref …` | | Storing `id.Index` alone | Names whichever entity reuses the index | Store the `EntityId`; `TryGetEntity` checks the version | | Reading a tracked component with `Get()` | The row counts as written, every `[Changed]` reader visits it | [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025); the generated property is `ref readonly` | | Writing an indexed component through `Get()` | The index keeps the old key | [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015) | | A `DynamicBuffer` copied out of an entity | Two entities share one list | [EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012) | | `Get()` on a component the entity may lack | `InvalidOperationException` | Use `HasX`, `TryGetX` or `TryGetRef` | ## Related - [Prefabs and cloning](https://ecs.xgamedev.net/en/docs/guide/prefabs): Define a kind of entity once, spawn it one at a time or in waves. - [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries): Select the entities that have a set of components. - [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes): Adding, removing, creating and destroying in the middle of a pass. - [ref and await](https://ecs.xgamedev.net/en/docs/guide/refs-and-await): Why refs into the tables never cross an `await`. --- # Prefabs and cloning > Define a kind of entity once as a Prefab and spawn it alone, in waves or as a linked group: derived prefabs, prefab buffers, EnsureCapacity and Entity.Clone. URL: https://ecs.xgamedev.net/en/docs/guide/prefabs Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/prefabs.md A server spawns the same kinds of entities again and again: a goblin, a fireball, a loot chest, a boss with its guards. A `Prefab` is the recipe of such a kind, a set of component values that belongs to no world, so no query or system ever sees it. `world.Instantiate(prefab)` creates an entity with a copy of every value, and `entity.Clone()` does the same from a living entity. ## When to use it > **Use it for** > > Kinds of entities defined once and spawned many times: NPC types, projectiles, items, read from code or from > configuration at startup. Waves of spawns (`Instantiate(prefab, span)`). Groups that always come together (a boss, > its mount and its guards). `Clone` for a runtime copy of a living entity: a mirror image, a slime that splits. > **Skip it for** > > One-off entities whose values differ every time: `CreateEntity(a, b, c)` is as fast and says more. A prefab > someone changes while another thread instantiates it. An `Entity` field meant to point at an entity of the target > world: give each instance its links after instantiating. ## How to use it ### Build the recipe The generated writers (`SetHealth`, `SetNpc`, ...) exist on `Prefab` too, and return the prefab, so a recipe is one chain. Keep prefabs in `static readonly` fields or a table of kinds. ```csharp public record struct Position(float X, float Y) : IComponent; public record struct Health(int Value, int Max) : IComponent, ITrackChanges; public record struct Attack(int Damage, int Cooldown) : IComponent; public struct Npc : IComponent; // a tag public static class Kinds { public static readonly Prefab Goblin = new Prefab() .SetPosition(0, 0).SetHealth(60, 60).SetAttack(4, 0).SetNpc(); public static readonly Prefab Troll = new Prefab() .Set(new Position(), new Health(300, 300), new Attack(12, 0)).SetNpc(); // or several values in one call } ``` ### Instantiate one The new entity gets a copy of every value. Write only what differs. ```csharp var world = new World(); var goblin = world.Instantiate(Kinds.Goblin); goblin.Position = new Position(100, 40); ``` ### Instantiate a wave `Instantiate(prefab, span)` fills the span with new entities: one pass through the structural gate, the prefab's row copied into consecutive rows at once, at most one table growth. ```csharp var wave = new Entity[500]; world.Instantiate(Kinds.Troll, wave); for (int i = 0; i < wave.Length; i++) wave[i].Position = new Position(i * 8, 0); ``` ### The `Prefab` API | Member | Effect | | ------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | `new Prefab()` | An empty recipe. | | `new Prefab(basePrefab)` | A copy of `basePrefab` (and its members) to change on its own. | | `Set(in T1 … in Tn)` → `Prefab` | Adds 1 to 9 values, or replaces the values of their types. | | `Remove()` → `Prefab` | Drops 1 to 9 components; missing ones are ignored. | | `Has()` | Whether the prefab has `T`. | | `Read()` → `ref readonly T` | The prefab's value; throws if it has none. | | `SetBuffer(params ReadOnlySpan)` → `Prefab` | A [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) with these elements. | | `AddMember()` → `Prefab` | A new [member](https://ecs.xgamedev.net/en/docs/guide/prefabs#prefab-groups) of the prefab's group. | | `Id` | The `EntityId` that names this member inside the group's components. | ### Generated members Like an entity, a prefab gets [named members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members) for every component of your project: | Declared | Generated on `Prefab` | Same as | | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | `record struct Health(int Value, int Max) : IComponent` | `prefab.Health` (`ref readonly`), `prefab.HasHealth`, `prefab.SetHealth(value, max)`, `prefab.RemoveHealth()` | `Read`, `Has`, `Set(new Health(value, max))`, `Remove` | | a tag (`struct Npc : IComponent`) | `prefab.IsNpc`, `prefab.SetNpc()`, `prefab.RemoveNpc()` | `Has`, `Set(new Npc())`, `Remove` | | a buffer element (`record struct Loot(int Item)`) | `prefab.SetLoot(new Loot(1), new Loot(2))`, `prefab.HasLoot`, `prefab.Loot` (`ref readonly`), `prefab.RemoveLoot()` | `SetBuffer(…)`, `Has`, `Read`, `Remove` of `DynamicBuffer` | ```csharp var elite = new Prefab().SetPosition(0, 0).SetHealth(500, 500).SetAttack(20, 0).SetNpc(); int max = elite.Health.Max; // read-only: change it with SetHealth if (elite.HasAttack) elite.SetAttack(25, 0); // replaces the value elite.RemoveNpc(); // the recipe drops the tag ``` The property is always read-only: a prefab changes only through `Set`, `Remove` and their generated forms, so there is no `TryGetX`, `GetOrAddX` or `WriteX` on a prefab. A prefab belongs to no world, so its writers are not structural changes of any world, and the analyzer does not report them inside `[ForEach]` methods or on other threads. ### Derived prefabs `new Prefab(basePrefab)` copies a prefab, members included, into a new one that changes on its own: a variant of a configured NPC. It is a copy, not inheritance: later changes of either prefab do not reach the other. ```csharp var chief = new Prefab(Kinds.Goblin).SetHealth(200, 200).SetAttack(9, 0); // a goblin, stronger var boss = world.Instantiate(chief); ``` ### Buffers in a prefab A prefab can carry a [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers): the generated `SetLoot(...)` (or `SetBuffer(...)`) gives it these elements, and every instance gets a list of its own with a copy of them. The element's members (`SetLoot`, `entity.Loot`, `WriteLoot`) are generated once some code of the project names `DynamicBuffer`. ```csharp public record struct Loot(int Item, int Count); public static class Chests { public static readonly Prefab Common = new Prefab().SetPosition(0, 0).SetLoot(new Loot(1, 3), new Loot(7, 1)); public static int Items(Entity chest) => chest.Read>().Count; // names the buffer type } ``` ```csharp var chest = world.Instantiate(Chests.Common); ref var items = ref chest.WriteLoot(); // this chest's own list items.Add(new Loot(9, 1)); int inRecipe = Chests.Common.Loot.Count; // still 2 ``` Do not `Set(new DynamicBuffer())` and fill it outside the prefab: a buffer value copied around shares its list ([EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012)). ### Prefab groups Some kinds always come together: a boss with its mount and its guards, a squad, a vehicle and its seats. Give the prefab members with `AddMember()`; each member is a prefab of its own. Instantiating the prefab, or any member, creates the whole group and returns the entity of the one you passed. Inside a group, an `EntityId` field that names a member (its `Id`) is rewritten to that member's new entity in every instance, so links survive the copy. Any other id becomes `EntityId.Null`: ids in a prefab name members only. ```csharp public record struct Follows(EntityId Target) : IComponent; public static class Bosses { public static readonly Prefab Warlord = Build(); static Prefab Build() { var warlord = new Prefab().SetHealth(5_000, 5_000).SetNpc(); var mount = warlord.AddMember().SetHealth(800, 800).Set(new ChildOf(warlord.Id)); warlord.AddMember().SetHealth(300, 300).Set(new ChildOf(warlord.Id), new Follows(mount.Id)); return warlord; } } ``` ```csharp var warlord = world.Instantiate(Bosses.Warlord); // three entities, linked to each other int guards = world.Index().Count(warlord); // 2 warlord.Destroy(); // ChildOf: destroying the parent destroys its children ``` `ChildOf` is EasyEcs's hierarchy link: see [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy). `Instantiate(group, span)` instantiates the group once per element. ### Reserve before the wave: `EnsureCapacity` `world.EnsureCapacity(prefab, count)` grows the table the prefab's instances go to, and the entity records, so the next `count` instances grow nothing. For a group, it reserves every member's table. Call it before the tick that spawns, so the wave pays no growth inside it. ```csharp world.EnsureCapacity(Kinds.Troll, 5_000); var army = new Entity[5_000]; world.Instantiate(Kinds.Troll, army); // no growth, no allocation ``` ### What a copy gets `Instantiate` and `Clone` copy every component value as it is: - **Values** are copied like any struct. A managed reference inside a component (a `string`, an array, a `List`) is copied as a reference, so the copies share what it points to. - **A `DynamicBuffer`** is the exception: every copy gets a list of its own with the same elements. - **[Value indexes](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations)** learn the new entity at once. - **[Tracked components](https://ecs.xgamedev.net/en/docs/guide/change-tracking)** count as written now: `[Changed]` methods see every new instance. A component the copy lacks is not a removal: `[Removed]` does not report it. - **Absent components stay absent.** A clone of an entity whose `Burning` was removed has no `Burning`. - **An `Entity` field** is copied as the handle it holds. In a prefab it names no entity of the target world, so give each instance its links after instantiating, or use an `EntityId` to a [member](https://ecs.xgamedev.net/en/docs/guide/prefabs#prefab-groups). ### Cloning a living entity `entity.Clone()` creates a new entity of the same world with the entity's current components, under the same rules. Use it for runtime copies of a live entity's state: a mirror image, a slime that splits in two, a player's state taken for a duel replay. For kinds of entities, use a prefab: it does not depend on some entity that may change or die. `Clone` throws for a handle that is not alive. ```csharp public static class Mirrors { public static Entity Mirror(Entity unit) => unit.IsAlive ? unit.Clone() : default; // health, statuses, bag } ``` ### Why a prefab is not an entity Some libraries keep templates as entities of the world: Unity Entities and Flecs tag them, and every query excludes that tag; Friflo clones an ordinary entity of the store, which its queries see like any other unless it is disabled. Either way the templates live among the entities that systems move, damage and replicate. In EasyEcs a `Prefab` is data outside every world: no query can see it, systems need no filter for it, and one prefab serves every world (several threads may instantiate it at once as long as nobody changes it meanwhile). ## Full example Two kinds of enemy, the second derived from the first, spawned one at a time, as a wave and by cloning. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent; // A tag: every enemy has it, whatever its kind. public struct Enemy : IComponent; ``` **Kinds.cs** ```csharp using EasyEcs; // The kinds of enemy, built once. // The generated writers return the prefab, so a recipe is one chain. public static class Kinds { public static readonly Prefab Goblin = new Prefab().SetPosition(0, 0).SetHealth(30).SetEnemy(); // A variant: a copy of the goblin with more health. public static readonly Prefab Chief = new Prefab(Goblin).SetHealth(80); } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); // One entity: a copy of every value of the recipe, then only what differs. Entity first = world.Instantiate(Kinds.Goblin); first.Position = new Position(10, 20); // A wave: a hundred copies in one pass. var wave = new Entity[100]; world.Instantiate(Kinds.Goblin, wave); Entity boss = world.Instantiate(Kinds.Chief); // Clone copies a living entity as it is now, not the recipe it came from. boss.Health = new Health(50); Entity twin = boss.Clone(); var enemies = QueryFilter.Create().With(); Console.WriteLine($"{world.Count(enemies)} enemies"); Console.WriteLine($"first at {first.Position}"); Console.WriteLine($"boss {boss.Health.Value} hp, twin {twin.Health.Value} hp"); // A prefab lives outside the world: the world counts only the entities made from it. Console.WriteLine($"{world.EntityCount} entities in the world"); ``` It prints: ```text 103 enemies first at Position { X = 10, Y = 20 } boss 50 hp, twin 50 hp 103 entities in the world ``` The twin has the boss's 50 health, not the chief's 80: a clone copies the entity, not its prefab. The two prefabs are not among the 103 entities. ## How to use it fast | Instead of | Do | Why | | ------------------------------------------------- | ----------------------------------------- | --------------------------------------------------- | | `Instantiate` in a loop for a wave | `Instantiate(prefab, span)` | One gate pass, consecutive rows copied at once | | Growing tables during the spawning tick | `EnsureCapacity(prefab, count)` before it | The wave allocates nothing | | `CreateEntity` then `Set` per component of a kind | A prefab | One row copy, the target table cached per prefab | | A new `Prefab` per spawn | One prefab per kind, kept in a field | Its table lookup is cached after the first instance | | Templates as hidden entities | A `Prefab` | No query pays to skip them | Spawning 1,000 entities of four components (one tracked) and destroying them, one `Instantiate` per entity against one `Instantiate(prefab, span)` (`PrefabBenchmark`): | Case | Mean | vs baseline | Allocated | | ---------------- | ------- | ----------- | --------- | | InstantiateEach | 49.7 μs | 1.00× | 0 B | | InstantiateBatch | 15.3 μs | 0.31× | 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, which clones a template entity of its store: 5,000 NPCs of six components spawned and destroyed: **Spawn 5,000 NPCs from a template and destroy them** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------ | ---------- | --------- | | EasyEcs | Instantiate | 164 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Instantiate | 276 μs | 1.68× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **A prefab** is a small private world with one row per member, allocated once when you build it. - **`Instantiate`:** one row copy, O(components). The first instance finds the target table; the world caches it per prefab table, so later instances go straight to it. - **`Instantiate(prefab, span)`:** O(count × components) with one gate pass and at most one table growth. - **A group:** O(members × components) per instance, plus the rewriting of member ids. - **`Clone`:** one row copy within the entity's own table. - **Allocations:** none after warm-up, except the list each `DynamicBuffer` copy gets. ## Pitfalls | Mistake | What happens | Caught by | | ----------------------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | An `Entity` field in a prefab's component | Every instance points at the same handle, of no world | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) (warning); use an `EntityId` to a member | | An `EntityId` of a world's entity in a prefab | Becomes `EntityId.Null` in every instance | Set links after instantiating | | Filling a `DynamicBuffer` value before `Set` | Every instance shares that list | [EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012); use `SetLoot(...)` | | `Instantiate(prefab)` in a counted loop | One copy per call instead of one wave | [EECS031](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs031): `Instantiate(prefab, span)` | | `Instantiate` on a thread that does not own the world | Races with the owner | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) | | `Instantiate` in a `[ForEach]` method without `Entity` or `World` | The pass assumes no structural change | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | | Changing a prefab while other threads instantiate it | Torn copies | Build prefabs at startup, then only read them | | `Clone()` on a destroyed entity | `InvalidOperationException` | Check `IsAlive` | ## Related - [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components): Handles, ids, `Set` / `Get` and the generated members prefabs share. - [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers): Lists per entity, which every instance gets a copy of. - [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy): `ChildOf` links and cascading destroy for prefab groups. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): New instances count as written: replication sends them. --- # 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. URL: https://ecs.xgamedev.net/en/docs/guide/queries Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/queries.md 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`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity)): the handler of a request or of a message to an actor. Counts and existence > checks (`Count`, `Any`). Bulk destroys (`DestroyEntities(filter)`). The filters themselves, which `[ForEach]` > methods take as attributes. > **Skip it for** > > Per-tick logic: write a [`[ForEach]` method](https://ecs.xgamedev.net/en/docs/guide/systems#foreach-methods) 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](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations), 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. ```csharp public static class Filters { public static readonly QueryFilter Active = QueryFilter.Create().Without().Without(); public static readonly QueryFilter Impaired = QueryFilter.Create().WithAny().WithAny(); // either } ``` ### Loop over the matches `world.Query(filter)` is a `foreach` loop. Each item hands out refs into the table, named after the components, and the entity. ```csharp 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(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 ```csharp int moving = world.Count(Filters.Active); bool anyImpaired = world.Any(Filters.Impaired); // stops at the first match int cleared = world.DestroyEntities(QueryFilter.Create().With()); ``` ### Which API | Need | Use | | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | Per-entity logic of a system | a [`[ForEach]` method](https://ecs.xgamedev.net/en/docs/guide/systems#foreach-methods) | | Arithmetic over many rows in a system | a [batch `[ForEach]` method](https://ecs.xgamedev.net/en/docs/guide/systems#batch-methods) (spans, SIMD) | | Heavy per-entity work in a system | [`[ForEach(Parallel = true)]`](https://ecs.xgamedev.net/en/docs/guide/systems#parallel-methods) | | A component the entity may or may not have | a [`Maybe` parameter](https://ecs.xgamedev.net/en/docs/guide/systems#maybe), or two methods split by `With` / `Without` | | A pass outside systems, as a method | a [`[ForEach]` runner](https://ecs.xgamedev.net/en/docs/guide/systems#foreach-outside-systems): a static method with a generated entry point | | The fastest ad-hoc loop | `world.ForEach(ref job, filter)` with a [struct job](https://ecs.xgamedev.net/en/docs/guide/queries#foreach-a-struct-job) | | Ad-hoc loop that needs the `Entity` | `world.ForEachEntity(ref job, filter)` | | Ad-hoc arithmetic over runs of rows | `world.ForEachBatch(ref job, filter)` | | A job on one entity (a request, a message) | [`entity.Run(ref job, filter)`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity) | | Ad-hoc heavy work on several threads | [`ForEachParallel` / `ForEachEntityParallel`](https://ecs.xgamedev.net/en/docs/guide/queries#on-several-threads-foreachparallel-and-foreachentityparallel) | | A convenient loop (tools, tests, handlers) | `foreach (var item in world.Query(filter))` | | "How many …?" / "Is there any …?" | `world.Count(filter)` / `world.Any(filter)` | | Destroy every match | `world.DestroyEntities(filter)` | | Only rows written or removed since a tick | `Changed(tick)` / `Removed(tick)` ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking)) | | Entities by a value, or pointing at an entity | `world.Index().Find(key)` ([indexes](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations)) | ### Filters | Filter | Selects | As a `[ForEach]` attribute | | ------------------------ | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | `With()` | entities that also have `T` (not passed in) | `[With]` | | `Without()` | entities that lack `T` | `[Without]` | | `WithAny()`, repeated | entities with at least one of the `WithAny` components | `[WithAny]`, repeated | | `Changed(since)` | entities whose tracked `T` was written at or after `since` | `[Changed]` (since the system's last run) | | `Removed(since)` | entities that lost tracked `T` at or after `since` and still lack it | `[Removed]` | | `InGroup(group)` | entities whose `T` is in one [group](https://ecs.xgamedev.net/en/docs/guide/groups) | none; 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: ```csharp public record struct Armor(int Value) : IComponent, ITrackChanges; public static class Replication { public static readonly QueryFilter Dirty = QueryFilter.Create().Changed(0); } ``` ```csharp ulong mark = world.ChangeTick; world.Update(); int dirty = world.Count(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()` ([what counts as a write](https://ecs.xgamedev.net/en/docs/guide/change-tracking#what-counts-as-a-write)). A loop may create, destroy, add and remove; the rules are in [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes). ### `ForEach`: a struct job A struct that implements `IForEach` is specialized for its type and inlined by the JIT: no delegate, no closure, no allocation. `[ForEach]` methods compile to exactly this. ```csharp public struct Integrate : IForEach, 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; } } ``` ```csharp var integrate = new Integrate(); world.ForEach(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](https://ecs.xgamedev.net/en/docs/guide/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` with `world.ForEachEntity` also receives the `Entity`, built from the table's entity rows without a lookup. - `IForEachBatch` with `world.ForEachBatch` receives runs of consecutive rows as spans, `Execute(EntitySpan entities, Span …)`, to vectorize with `Vector` (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. ```csharp using System.Numerics; using System.Runtime.InteropServices; public struct KillTheWounded : IForEachEntity { 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 { public static int Writes => 1; public void Execute(EntitySpan entities, Span positions, Span velocities) { // Two floats each: as Vector spans, every lane is one coordinate var p = MemoryMarshal.Cast>(positions); var v = MemoryMarshal.Cast>(velocities); for (int i = 0; i < p.Length; i++) p[i] += v[i]; var pf = MemoryMarshal.Cast(positions); var vf = MemoryMarshal.Cast(velocities); for (int i = p.Length * Vector.Count; i < pf.Length; i++) pf[i] += vf[i]; // the rows left over } } ``` ```csharp var kill = new KillTheWounded(); world.ForEachEntity(ref kill, QueryFilter.Create().Without()); var drift = new Drift(); world.ForEachBatch(ref drift, Filters.Active); ``` ### One entity: `entity.Run` Code that handles one entity at a time runs a job on it with `entity.Run(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. ```csharp public static class Hits { // Built once: the filter is a value, kept in a field. public static readonly QueryFilter Alive = QueryFilter.Create().Without(); } public struct TakeHit : IForEachEntity { 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 } } ``` ```csharp var hit = new TakeHit { Damage = 30 }; bool applied = unit.Run(ref hit, Hits.Alive); // false: dead, no Health, or not alive ``` Without a filter, `entity.Run(ref job)` checks only that the entity is alive and has the components. A job that only reads declares `Writes => 0`: ```csharp public struct ReadHealth : IForEachEntity { 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; } ``` ```csharp var read = new ReadHealth(); if (unit.Run(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](https://ecs.xgamedev.net/en/docs/guide/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(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](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010)), in a `[ForEach]` method that takes no `Entity` or `World` ([EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013)) and off the world's owner thread ([EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014)). An actor is the typical user: each message handler finds the actor's entity (through a [value index](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations)) and runs one job on it. The [Actors sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/Actors) 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` filter and a structural change in the middle, against the same work written through the handle (`Has()`, a `TryGetRef` per component, the ref taken again after the change) (`SingleEntityBenchmark`): | Case | Components | Filtered | Structural | Mean | vs baseline | Allocated | | ----------- | ---------- | -------- | ---------- | ------- | ----------- | --------- | | Handwritten | 1 | False | False | 15.9 μs | 1.00× | 0 B | | Run | 1 | False | False | 14.0 μs | 0.88× | 0 B | | Handwritten | 1 | False | True | 33.5 μs | 1.00× | 0 B | | Run | 1 | False | True | 27.9 μs | 0.84× | 0 B | | Handwritten | 1 | True | False | 16.2 μs | 1.00× | 0 B | | Run | 1 | True | False | 14.8 μs | 0.91× | 0 B | | Handwritten | 1 | True | True | 32.8 μs | 1.00× | 0 B | | Run | 1 | True | True | 28.1 μs | 0.86× | 0 B | | Handwritten | 3 | False | False | 23.4 μs | 1.00× | 0 B | | Run | 3 | False | False | 16.1 μs | 0.69× | 0 B | | Handwritten | 3 | False | True | 34.1 μs | 1.01× | 0 B | | Run | 3 | False | True | 33.5 μs | 0.99× | 0 B | | Handwritten | 3 | True | False | 21.6 μs | 1.00× | 0 B | | Run | 3 | True | False | 20.9 μs | 0.97× | 0 B | | Handwritten | 3 | True | True | 31.2 μs | 1.00× | 0 B | | Run | 3 | True | True | 32.4 μs | 1.04× | 0 B | | Handwritten | 5 | False | False | 27.5 μs | 1.00× | 0 B | | Run | 5 | False | False | 24.4 μs | 0.89× | 0 B | | Handwritten | 5 | False | True | 35.6 μs | 1.00× | 0 B | | Run | 5 | False | True | 37.7 μs | 1.06× | 0 B | | Handwritten | 5 | True | False | 28.2 μs | 1.00× | 0 B | | Run | 5 | True | False | 24.3 μs | 0.86× | 0 B | | Handwritten | 5 | True | True | 35.2 μs | 1.01× | 0 B | | Run | 5 | True | True | 37.0 μs | 1.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. ```csharp public struct Heal : IForEach, INoStructuralChanges { public static int Writes => 1; public void Execute(ref Health health) => health.Value = Math.Min(health.Value + 10, 100); } ``` ```csharp var heal = new Heal(); world.ForEachParallel(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)]`](https://ecs.xgamedev.net/en/docs/guide/systems#parallel-methods) 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`. **Components.cs** ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; // Two states as tags. A frozen unit does not move; a frozen or burning unit is slowed. public struct Frozen : IComponent; public struct Burning : IComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Halves the velocity of every unit that is frozen, burning, or both. public class SlowSystem : EcsSystem { [ForEach, WithAny, WithAny] static void Slow(ref Velocity velocity) { velocity = new Velocity(velocity.X / 2, velocity.Y / 2); } } // Moves every unit that is not frozen. [UpdateAfter] public class MoveSystem : EcsSystem { [ForEach, Without] static void Move(ref Position position, in Velocity velocity) { position = new Position(position.X + velocity.X, position.Y + velocity.Y); } } ``` **Queries.cs** ```csharp using EasyEcs; // A filter is a value: build it once and keep it in a static readonly field. public static class Filters { public static readonly QueryFilter Moving = QueryFilter.Create().Without(); } // A struct job: the fastest pass outside systems, with no delegate. public struct SumX : IForEach { public float Sum; public void Execute(ref Position position) { Sum += position.X; } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); world.AddSystem(); world.AddSystem(); world.CreateEntity(new Position(0, 0), new Velocity(1, 0)); world.CreateEntity(new Position(0, 0), new Velocity(0, 1), new Frozen()); world.CreateEntity(new Position(0, 0), new Velocity(2, 2), new Burning()); world.CreateEntity(new Position(9, 9)); world.Update(); // Outside systems: loop over the matches. Each item hands out refs into the table. foreach (var item in world.Query(Filters.Moving)) { Console.WriteLine($"{item.Entity}: {item.Position}"); } // Count and test without reading any component value. int moving = world.Count(Filters.Moving); bool anyFrozen = world.Any(); Console.WriteLine($"moving: {moving}, any frozen: {anyFrozen}"); // Run the struct job over every position, the unit without a velocity too. var sumX = new SumX(); world.ForEach(ref sumX); Console.WriteLine($"sum of X: {sumX.Sum}"); ``` It prints: ```text 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 of | Do | Why | | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | A `Query` loop every tick | A `[ForEach]` method in a system | Generated struct job, ordered and scheduled | | `QueryFilter.Create()…` at every call | A `static readonly` filter | The cache key is built once | | A `Query` that only reads tracked components | A job with `Writes => 0`, or `in` parameters | Items stamp what they hand out | | `ForEachEntity` when the entity is rarely used | A batch job with `EntitySpan` | Handles built only for the rows that need one | | A scalar loop over many rows | A batch job with `Vector` | The JIT does not vectorize on its own | | `Count(...) > 0` | `Any(...)` | Stops at the first match ([EECS032](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs032)) | | Several `Get` / `TryGetRef` and a `Has()` per request | [`entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity) with a `static readonly` filter | One lookup; the refs are carried across structural changes | | Scanning for a key | A [value index](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) | O(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`): | Case | Mean | vs baseline | Allocated | | ------------------ | ------- | ----------- | --------- | | RawArrayWrite | 12.8 μs | 1.01× | 0 B | | ForEachSystemWrite | 9.13 μs | 0.72× | 0 B | | ForEachWrite | 9.55 μs | 0.75× | 0 B | | QueryWrite | 18.9 μs | 1.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`): | Case | Mean | vs baseline | Allocated | | -------------- | ------- | ----------- | --------- | | Runner | 33.7 μs | 1.00× | 0 B | | HandWrittenJob | 56.7 μs | 1.69× | 0 B | | Query | 145 μs | 4.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`): | Case | Mean | vs baseline | Allocated | | ------------ | ------- | ----------- | --------- | | FilterAtCall | 74.8 ns | 1.00× | 0 B | | FilterOnce | 21.6 ns | 0.29× | 0 B | | NoFilter | 42.9 ns | 0.57× | 0 B | | PastTheMemo | 88.0 ns | 1.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`): | Case | Mean | vs baseline | Allocated | | --------------- | ------- | ----------- | --------- | | PassOverTheFew | 386 ns | — | 0 B | | QueryTheFew | 365 ns | — | 0 B | | CountTheFew | 13.6 ns | — | 0 B | | PassOverTheRest | 52.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** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------ | ------- | ---------- | --------- | | EasyEcs | Iterate1 | 37.7 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate1 | 59.9 μs | 1.59× | 0 B | | EasyEcs | Iterate2 | 253 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2 | 257 μs | 1.02× | 0 B | | EasyEcs | Iterate2Simd | 69.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2Simd | 80.7 μs | 1.16× | 0 B | | EasyEcs | With | 11.3 μs | 1.00× | 0 B | | Friflo.Engine.ECS | With | 16.6 μs | 1.46× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## 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 | Mistake | What happens | Caught by | | ------------------------------------------------------------ | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `await` inside a `Query` loop | Does not compile: items are ref structs | The C# compiler | | Storing a query item | Does not compile; keep `item.Entity` | The C# compiler | | A `Query` loop that only reads tracked components | Every visited row counts as written | Use a job with `Writes => 0` or `Read()` | | `INoStructuralChanges` on a job that changes structure | `InvalidOperationException` at the change | At run time | | Structural change in a batch job | `InvalidOperationException`: the spans point into the tables | At run time ([EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) for `[ForEach]` methods) | | A parallel job that writes a singleton or another entity | Races between chunks | Code review ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) for `[ForEach]` methods) | | `Changed` and `Removed` with different ticks in one filter | `ArgumentException` | At run time | | `Update()` called from inside a query loop of the same world | Undefined order of passes | Code review; [EECS034](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs034) when called from a system | | An `entity.Run` job without `Writes` | The default (-1) stamps every tracked component the job takes | Declare `Writes` (`0` for a job that only reads) | | `INoStructuralChanges` on a `Run` job that changes structure | `InvalidOperationException` at the change | At run time | | Treating `false` from `Run` as "dead" | It also means a missing component or a filter that failed | Code review: test `IsAlive` | | `QueryFilter.Create()…` built at every `Run` or query call | The filter is rebuilt and looked up at every call | Code review: a `static readonly` field | | `entity.Run` inside a parallel `[ForEach]` method | Its job may change structure from several threads | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) | ## Related - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): The same filters as attributes, ordered and scheduled. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): `Changed` and `Removed`: only what changed since a tick. - [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes): What a pass sees when entities change under it. - [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations): Find entities by value without a scan. --- # Systems and [ForEach] > Write per-tick logic as stateless systems with [ForEach] methods: parameters, filters, ordering, groups, batch and parallel methods, runners and errors. URL: https://ecs.xgamedev.net/en/docs/guide/systems Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/systems.md A system is one job of the server's tick: move units, apply burning damage, kill the dead, send state to clients. It derives from `EcsSystem`, keeps no state of its own (state is in components and singletons) and never references another system. Its loops are `[ForEach]` methods: a static method whose parameters name the components it reads and writes, which the source generator compiles into a struct job as fast as a hand-written loop. ## When to use it > **Use it for** > > All per-tick behavior: one responsibility per system, one `[ForEach]` method per loop, ordering with > `[UpdateAfter]`, groups for different cadences (input whenever it arrives, simulation at a fixed tick), > `UpdateInterval` for work that runs every N-th tick. [Group filters](https://ecs.xgamedev.net/en/docs/guide/systems#group-filters) keep a whole group to one kind > of entity, and a generic group interface gives each type its own group (one group per actor type). > **Skip it for** > > A one-off pass that a request or a tool runs between ticks: write a [`[ForEach]` runner](https://ecs.xgamedev.net/en/docs/guide/systems#foreach-outside-systems) > or a [query](https://ecs.xgamedev.net/en/docs/guide/queries). State that must survive between ticks: put it in a component or a > [singleton](https://ecs.xgamedev.net/en/docs/guide/singletons), never in a system field ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007)). ## How to use it ### Write the system Each `[ForEach]` method runs once per matching entity, every update. `ref` parameters are written, `in` parameters read; attributes filter the entities. ```csharp public record struct Burning(int Ticks, int Damage) : IComponent; public struct Player : IComponent; // a tag public record struct BurnTotals(int Damage) : ISingletonComponent; public class BurnSystem : EcsSystem { [ForEach, Without] // living entities only static void Burn(ref Health hp, in Burning burning, ref BurnTotals totals) { hp.Value -= burning.Damage; totals.Damage += burning.Damage; } } [UpdateAfter] // damage first, then death public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp) { if (hp.Value <= 0) unit.SetDead(); // a structural change, applied now } } ``` ### Add it and update ```csharp var world = new World(); world.AddSingleton(); // BurnSystem reads it: add it before the first update world.AddSystem(); // added first, runs second: [UpdateAfter] orders it world.AddSystem(); world.CreateEntity(new Health(5), new Burning(3, 10), new Player()); world.Update(); // one tick int dealt = world.BurnTotals.Damage; // 10 ``` ### Lifecycle | Hook or member | When | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `OnCreate()` | once, when the system is added (`world.AddSystem()` / `AddSystem(system)`) | | `OnUpdate()` | every update of its group, before its `[ForEach]` methods | | `[ForEach]` methods | every update, after `OnUpdate`, in source order (a base class's first) | | `OnDestroy()` | once, on `world.RemoveSystem()` or `world.Dispose()` (reverse order) | | `World` | the owning world, set before `OnCreate` | | `Enabled` | `false` skips the system in `Update()` and `Update()` | | `LastRunTick` | the change tick of its last run ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking#ticks)) | | `Stats`, `Error` | [measurements](https://ecs.xgamedev.net/en/docs/guide/systems#measuring-systems) and the [exception that switched it off](https://ecs.xgamedev.net/en/docs/guide/systems#errors) | `AddSystem()` returns the system; `GetSystem()` finds one (for tools and tests, never from another system: [EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008)); `world.Systems` lists every system without allocating; `UpdateCount` counts the default group's updates. A system belongs to one world: adding it to a second throws. ```csharp var burn = world.GetSystem(); foreach (var system in world.Systems) Console.WriteLine(system.GetType().Name); world.RemoveSystem(); // OnDestroy runs long updates = world.UpdateCount; ``` ### One update ```mermaid flowchart TB U["world.Update()"] --> S{"enabled and due?"} S -- no --> N["next system"] S -- yes --> O["OnUpdate()"] O --> F["[ForEach] methods, in source order"] F --> N ``` Systems run in registration order unless ordered. Structural changes apply at once, so later methods and systems of the same update see them. Everything runs on the thread that calls `Update()`, unless `WorldOptions.ParallelSystems` runs systems with no order and no conflict between them at the same time ([Threading](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems)); the result is the same as running them in order. ### Ordering `[UpdateBefore]` and `[UpdateAfter]` move a system just before or after system `T` (and its subclasses) of the same group, whatever the order they were added in; the others keep their relative order. The order is resolved when a system is added: a cycle throws there and the system stays out. The analyzer reports the cycles ([EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019)) and cross-group orderings ([EECS020](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs020)) it can see. ### `UpdateInterval` and `UpdatePhase` A system that overrides `UpdateInterval` runs every N-th update of its group: on the updates whose count is a multiple of N, so first on the N-th. `UpdatePhase` (0 to N - 1) shifts which of the N updates it takes, so systems with the same interval spread their work instead of all running on the same tick. Both must be constants ([EECS018](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs018)); to pause a system, set `Enabled`. ```csharp public record struct Autosave(long Count) : ISingletonComponent; public class SaveSystem : EcsSystem { public override int UpdateInterval => 60; // every 60th update public override int UpdatePhase => 30; // half a cycle after the others with the same interval protected override void OnUpdate() => World.GetOrAddAutosave().Count++; } ``` ### `[ForEach]` methods A `[ForEach]` method is declared in a class that derives from `EcsSystem` (no `partial` needed). It may be static or an instance method. Its parameters say what it runs over: | Parameter | Meaning | | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | `ref T` / `in T` / `ref readonly T`, `T : IComponent` | 1 to 9 components: `ref` to write, `in` to read | | `ref T` / `in T`, `T : ISingletonComponent` | the world's singleton, resolved once per pass; throws if it was not added | | `Entity` | the current entity, for structural changes and lookups | | `World` | the world (for creating entities, other singletons) | | [`Maybe`](https://ecs.xgamedev.net/en/docs/guide/systems#maybe) | a component the entity may lack | | `Span` / `ReadOnlySpan`, `EntitySpan` | a [batch method](https://ecs.xgamedev.net/en/docs/guide/systems#batch-methods): runs of rows at once | | Attribute | Meaning | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `[ForEach]` | run the method for every matching entity; `Parallel = true` for [several threads](https://ecs.xgamedev.net/en/docs/guide/systems#parallel-methods) | | `[With]` | the entity must have `T`, not passed in; repeatable | | `[Without]` | the entity must not have `T`; repeatable | | `[WithAny]` | the entity must have at least one of the method's `[WithAny]` components | | `[Changed]` | `T` (`ITrackChanges`) was written since the system last ran ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking)) | | `[Removed]` | the entity lost `T` (`ITrackChanges`) since the system last ran ([removal detection](https://ecs.xgamedev.net/en/docs/guide/change-tracking#removal-detection)) | With no component parameter, the first `[With]` (else the first `[Changed]`) names the queried component: ```csharp public class CorpseCleanup : EcsSystem { [ForEach, With] static void Remove(Entity corpse) => corpse.Destroy(); } ``` A method that is static, takes no `World` and uses its `Entity` (if any) only to read (`Id`, `IsAlive`, `Has`, `Get`, `Read`, `TryGet`, `TryGetRef`) cannot change structure: its job implements `INoStructuralChanges`, walks each table with no per-entity check, and may share a parallel stage with other systems. A method that may change structure runs alone, and each entity is still visited at most once per pass ([Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes)). Methods run in source order, and a derived system runs its base class's `[ForEach]` methods first. Keep a system's methods in one file: across the files of a partial class the order is per file. #### Optional components: `Maybe` `Maybe` takes a component the entity may lack: the method visits every entity with its other components, and `HasValue` says whether this one also has `T`. Writing through `Value` writes `T` (a tracked one is stamped); reading only is a read. ```csharp public record struct Shield(int Bonus) : IComponent; public record struct Stamina(int Value) : IComponent; public class Regeneration : EcsSystem { [ForEach] static void Regenerate(ref Stamina stamina, Maybe shield) => stamina.Value += shield.HasValue ? 1 + shield.Value.Bonus : 1; } ``` It saves writing two methods when the optional part is small. In the hottest loops, two methods split by `[With]` and `[Without]` are faster: no test per row (see the numbers below). A method that changes no structure finds the optional column once per run of rows; one that changes structure looks it up per entity. ### Batch methods A method whose component parameters are spans receives runs of consecutive matching rows: element `i` of every span belongs to the same entity, and a table where every row matches is one call. Its other parameters can be singletons and an `EntitySpan` (`entities[i]` is built only when indexed), nothing else ([EECS009](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs009)). The spans point into the tables, so the structure is frozen while it runs: a change throws, and [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) reports it at compile time. ```csharp using System.Numerics; using System.Runtime.InteropServices; public class DriftSystem : EcsSystem { [ForEach, Without] static void Drift(Span positions, ReadOnlySpan velocities) { // The JIT does not vectorize loops on its own. Two floats each: as Vector, every lane is a coordinate var p = MemoryMarshal.Cast>(positions); var v = MemoryMarshal.Cast>(velocities); for (int i = 0; i < p.Length; i++) p[i] += v[i]; var pf = MemoryMarshal.Cast(positions); var vf = MemoryMarshal.Cast(velocities); for (int i = p.Length * Vector.Count; i < pf.Length; i++) pf[i] += vf[i]; // the rows left over } } ``` A scalar loop over spans gains little over a per-entity method; write a batch method to vectorize. ### Parallel methods `[ForEach(Parallel = true)]` cuts the matching rows into chunks (about four per thread, a multiple of 64 rows, between 1,024 and `World.ParallelChunkRows` = 16,384) and runs them on the calling thread plus up to `WorldOptions.MaxDegreeOfParallelism - 1` thread-pool threads. It is for heavy per-entity work (path finding, steering, AI scoring) over tens of thousands of entities; for light work the hand-off costs more than it saves. ```csharp public record struct Clock(float Time) : ISingletonComponent; public class SteeringSystem : EcsSystem { [ForEach(Parallel = true), Without] static void Steer(ref Velocity velocity, in Position position, in Clock clock) => velocity = new Velocity(MathF.Cos(clock.Time + position.X), MathF.Sin(clock.Time + position.Y)); } ``` The method must be able to run on several threads at once ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010)): no structural change, per entity (not a batch method), singletons only as `in`. It also must not write what another row's run reads, such as another entity through `Get`. Fewer than two chunks run on the calling thread. It allocates nothing after its first update. ### System groups `world.Update()` runs the default group. A system marked `[UpdateInGroup]` (`TGroup` a `struct : ISystemGroup`) runs only when `world.Update()` is called. Use groups for different cadences: a server can apply input whenever it arrives and simulate at a fixed tick. ```csharp public struct InputGroup : ISystemGroup; [UpdateInGroup] public class ApplyInputSystem : EcsSystem { [ForEach, With] static void Apply(ref Velocity velocity) => velocity = new Velocity(velocity.X * 0.9f, velocity.Y * 0.9f); } ``` ```csharp world.AddSystem(); world.Update(); // whenever input arrives world.Update(); // fixed tick: the default group ``` Ordering, `UpdateInterval`, `UpdatePhase` and `Enabled` apply within each group, and the attribute is inherited. Updating a group with no systems does nothing. #### Group filters `[With]`, `[Without]` and `[WithAny]` on the group struct join every `[ForEach]` method of its systems: a whole group can leave frozen or inactive entities out without repeating the filter on each method. A group's `[WithAny]` joins the method's own `[WithAny]` set, so it widens the "at least one of" test: a group with `[WithAny
]` and a method with `[WithAny]` select entities with `A` or `B`. Queries a system makes in `OnUpdate` are its own, and [`[ForEach]` runners](https://ecs.xgamedev.net/en/docs/guide/systems#foreach-outside-systems) belong to no group, so no group filter applies to them. A filter attribute on a struct that is not a group is a compile error ([EECS023](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs023)). ```csharp [Without] public struct Gameplay : ISystemGroup; // no method of the group sees a frozen entity [UpdateInGroup] public class MoveSystem : EcsSystem { [ForEach] static void Move(ref Position p, in Velocity v) => p = new Position(p.X + v.X, p.Y + v.Y); } ``` A group that a generic interface describes cannot name its filter in an attribute: C# refuses a type parameter as the type argument of an attribute (`[With>]` on `IActor` is CS8968). The group implements `IGroupWith` or `IGroupWithout` instead, here or through an interface, and gets the same filter: one interface then gives every actor type its group. The actor pattern goes one step further: one type per kind of actor is at once its key component (indexed, so a message finds its actor), its system group and, through the interface, the group's filter: ```csharp public struct In : IComponent; // the tag of one kind of actor public interface IActor : IComponent, IIndexed, ISystemGroup, IGroupWith> where TSelf : struct, IActor, IEquatable; // IIndexed requires IEquatable // Key component, index key and system group in one type. Key is implemented explicitly: a public // Key property would be printed by the record's ToString(), which would print Key again, forever. public readonly record struct Shop(long Id) : IActor { Shop IIndexed.Key => this; } public record struct Stock(int Items) : IComponent; [UpdateInGroup] public class RestockSystem : EcsSystem { [ForEach] // only entities tagged In static void Restock(ref Stock stock) => stock.Items = Math.Max(stock.Items, 10); } ``` ```csharp world.AddSystem(); world.CreateEntity(new Shop(7), new In(), new Stock(0)); world.Update(); // the shop systems, over the shop actors only bool open = world.ShopIndex.TryFind(new Shop(7), out var shop); // a message finds its actor ``` The [Actors sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/Actors) is the whole program: two kinds of actors, messages handled with [`entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity), activation and saving. ### Generic systems A system can be generic. Each closed type is a system of its own, with its own generated job and access set, so `CountOf` and `CountOf` are added, ordered and scheduled independently. A closed generic system can be a base class: its `[ForEach]` methods run before the subclass's. A closed type the code never names (built by reflection) has its code closed on first use. ```csharp public record struct Tally(int Count) : ISingletonComponent; public class CountOf : EcsSystem where T : struct, IComponent // world.AddSystem>() { [ForEach] static void Count(in T component, ref Tally tally) => tally.Count++; } ``` A system's `[ForEach]` method itself cannot be generic: nothing would supply its type arguments ([EECS004](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs004)). Attribute type arguments cannot name type parameters (C# rule CS8968), so filters such as `[With]` name concrete types. ### `[ForEach]` outside systems A `[ForEach]` method in a type that is not an `EcsSystem` is a runner: a pass the host runs itself, for example between ticks to answer a request. The generator writes an entry point for it, a static method of the type with the same name that takes the `World` and then the method's other values, and runs the job once over the world. Besides components, singletons, `Entity` and `World`, a runner may take values of any other type; the entry point takes them from the caller, `ref` ones included, so a runner can return results through them. ```csharp public record struct Gold(int Amount) : IComponent, ITrackChanges; public static class Reports { [ForEach, Without] static void SumHealth(in Health hp, ref long total) => total += hp.Value; [ForEach, Changed] static void Rich(in Gold gold, ref int count, int threshold) { if (gold.Amount >= threshold) count++; } } ``` A generic runner counts the living entities that have any component: ```csharp public static class Census { [ForEach, Without] static void CountAlive(in T component, ref int count) where T : struct, IComponent => count++; } ``` ```csharp long total = 0; Reports.SumHealth(world, ref total); // the generated entry point ulong mark = world.ChangeTick; int rich = 0; Reports.Rich(world, mark, ref rich, 1_000); // [Changed]: the tick comes after the world int alive = 0; Census.CountAlive(world, ref alive); // a generic runner: the type arguments first ``` - The method must be static ([EECS005](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs005)); it may be private, and the entry point is public when the types it names are public. - With `[Changed]` or `[Removed]` the entry point takes the tick to look back from, since a runner has no last run of its own. - Runners may be generic, or members of a generic type: the entry point takes the type arguments. - No [group filter](https://ecs.xgamedev.net/en/docs/guide/systems#group-filters) applies to a runner: it belongs to no group. - Batch and parallel runners follow the rules of [batch methods](https://ecs.xgamedev.net/en/docs/guide/systems#batch-methods) and [parallel methods](https://ecs.xgamedev.net/en/docs/guide/systems#parallel-methods). - The entry point must not collide with another method of the type ([EECS021](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs021)), and a local function cannot be a runner ([EECS024](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs024)). - Call it on the world's owner thread, like any structural code. ### Measuring systems With `WorldOptions.MeasureSystems`, every run of a system (its `OnUpdate` plus its `[ForEach]` methods) is timed, and `system.Stats` holds `Runs`, `Last`, `Total` and `Average`. It costs two timestamp reads per system run, and nothing when off. Read it between updates, for example from a diagnostics endpoint: ```csharp var measured = new World(new WorldOptions { MeasureSystems = true }); measured.AddSingleton(); measured.AddSystem(); measured.Update(); var stats = measured.GetSystem().Stats; Console.WriteLine($"burn: {stats.Last.TotalMicroseconds} μs, average {stats.Average.TotalMicroseconds} μs over {stats.Runs} runs"); ``` ### Errors By default an exception thrown by a system propagates out of `Update()` (and out of `Dispose()` for `OnDestroy`). With `SystemErrors = SystemErrorPolicy.Disable`, the failing system is switched off, its exception is kept in `system.Error`, and the update goes on with the next system. A failure is data: read it between updates. Setting `Enabled = true` clears `Error` and retries the system. A system that failed still counts as run: its `LastRunTick` moves on, so its `[Changed]` methods do not visit again the rows written before the failed run. ```csharp var guarded = new World(new WorldOptions { SystemErrors = SystemErrorPolicy.Disable }); guarded.AddSingleton(); guarded.AddSystem(); guarded.Update(); foreach (var system in guarded.Systems) // a health check, between updates if (system.Error is { } error) Console.Error.WriteLine($"{system.GetType().Name} is off: {error.Message}"); ``` `Update()` after `Dispose()` throws `ObjectDisposedException`. What else a running world can tell you (its tables, an entity's components, memory): [Debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics). ## Full example A group with a filter, two systems ordered inside it, and a method filter: three units move, one of them on the ground and one frozen. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; // A unit on the ground slows down; a frozen unit does not move at all. public struct Grounded : IComponent; public struct Frozen : IComponent; // The simulation group: none of its methods sees a frozen unit. [Without] public struct Simulation : ISystemGroup; ``` **Systems.cs** ```csharp using EasyEcs; // Moves every unit by its velocity. [UpdateInGroup] public class MoveSystem : EcsSystem { [ForEach] static void Move(ref Position position, in Velocity velocity) { position = new Position(position.X + velocity.X, position.Y + velocity.Y); } } // Halves the velocity of grounded units, before they move. [UpdateInGroup, UpdateBefore] public class FrictionSystem : EcsSystem { [ForEach, With] static void Slow(ref Velocity velocity) { velocity = new Velocity(velocity.X / 2, velocity.Y / 2); } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); // Added in the wrong order on purpose: [UpdateBefore] still runs friction first. world.AddSystem(); world.AddSystem(); var flying = world.CreateEntity(new Position(0, 0), new Velocity(8, 0)); var walking = world.CreateEntity(new Position(0, 0), new Velocity(8, 0), new Grounded()); var frozen = world.CreateEntity(new Position(0, 0), new Velocity(8, 0), new Frozen()); for (int tick = 1; tick <= 2; tick++) { // Runs the systems of the Simulation group only. world.Update(); float x1 = flying.Position.X; float x2 = walking.Position.X; float x3 = frozen.Position.X; Console.WriteLine($"tick {tick}: flying at {x1}, walking at {x2}, frozen at {x3}"); } // World.Systems lists the systems in the order they run. foreach (var system in world.Systems) { Console.WriteLine($"run order: {system.GetType().Name}"); } ``` It prints: ```text tick 1: flying at 8, walking at 4, frozen at 0 tick 2: flying at 16, walking at 6, frozen at 0 run order: FrictionSystem run order: MoveSystem ``` The frozen unit never moves: the group's `[Without]` keeps it out of every method. Friction runs before the move although it was added second, so the grounded unit loses half its speed before each step. ## How to use it fast | Instead of | Do | Why | | --------------------------------------------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | `ref` on a component the method only reads | `in` ([EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025)) | The system can share a stage; a tracked component is not stamped | | An `Entity` or `World` parameter the method does not need | Drop it ([EECS026](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs026)) | The job skips structural bookkeeping and may run in parallel | | An instance `[ForEach]` method | A static one ([EECS029](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs029)) | Proven not to change structure: may share a stage, no per-row checks | | A scalar loop over many rows | A batch method with `Vector` | SIMD over whole runs of rows | | `Maybe` in the hottest loop | Two methods with `[With]` / `[Without]` | No presence test per row | | `Parallel = true` on light work | A plain `[ForEach]` | The hand-off costs more than it saves | | A filter repeated on every method of a cadence | A [group filter](https://ecs.xgamedev.net/en/docs/guide/systems#group-filters) | Written once | | Work every tick that could wait | `UpdateInterval` and `UpdatePhase` | Spread over ticks | A `[ForEach]` system against two plain arrays, `Position += Velocity` over 10,000 entities (`MicroBenchmarks`): | Case | Mean | vs baseline | Allocated | | ------------------ | ------- | ----------- | --------- | | RawArrayWrite | 12.8 μs | 1.01× | 0 B | | ForEachSystemWrite | 9.13 μs | 0.72× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. An optional component, 100,000 units of which half have a shield: one method with `Maybe` against two methods split by `With` / `Without` (`MaybeBenchmark`): | Case | Mean | vs baseline | Allocated | | ---------- | ------- | ----------- | --------- | | OneMethod | 130 μs | 1.01× | 0 B | | TwoMethods | 41.8 μs | 0.32× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Heavy steering over 100,000 entities, `[ForEach]` and `[ForEach(Parallel = true)]`, and the same work as an ad-hoc entity job (`ParallelForEachBenchmark`): | Case | Parallel | Mean | vs baseline | Allocated | | --------- | -------- | ------- | ----------- | --------- | | Tick | False | 1.68 ms | — | 0 B | | EntityJob | False | 1.92 ms | — | 0 B | | Tick | True | 884 μs | — | 0 B | | EntityJob | True | 896 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Four systems registered in run order, against the same four registered backwards and ordered by `[UpdateAfter]`: the order is resolved when they are added (`OrderingBenchmark`): | Case | Mean | vs baseline | Allocated | | ---------- | ------- | ----------- | --------- | | Registered | 20.9 μs | 1.01× | 0 B | | Ordered | 20.8 μs | 1.01× | 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: a method that takes the `Entity` per row, a batch method that builds handles only where needed, and a method that writes a singleton: **Per pass, 100,000 entities** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------- | ---------- | --------- | | EasyEcs | Entity | 49.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Entity | 67.2 μs | 1.37× | 0 B | | EasyEcs | EntityBatch | 38.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | EntityBatch | 37.0 μs | 0.96× | 0 B | | EasyEcs | Singleton | 212 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Singleton | 222 μs | 1.05× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **A `[ForEach]` method** is a struct job the JIT inlines into the row loop: no delegate, no allocation. - **Per system and update:** the `OnUpdate` call, one call per generated job, and one query-cache lookup per method. - **A group's filters** (`[With]`, `[Without]`, `[WithAny]` on the group type, `IGroupWith`, `IGroupWithout`) are read by the generator, so they cost nothing at run time. The tables they exclude cost nothing per update: a query's cache holds only the tables that match, so the tables of other kinds of entities in the world (other actor types) are never walked by the group's systems. - **Singleton parameters** are resolved once per pass, not per entity. - **Ordering** is resolved when systems are added: an update pays nothing for it. - **`MeasureSystems`** costs two timestamp reads per system run; nothing when off. - **Parallel methods** allocate nothing after their first update; the runner's work items are reused. - **Generated code** is registered by a module initializer: systems need no `partial`, no registration call and no reflection at update time. ## Pitfalls | Mistake | What happens | Caught by | | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | A mutable field in a system | State nothing else can see, save or restore | [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007) | | A system referencing another system | The two can no longer change apart | [EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008) | | A parameter of another type in a system's method | Nothing can supply it | [EECS002](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs002) | | No component and no `[With]` | Nothing names what to iterate | [EECS003](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs003) | | A generic `[ForEach]` method in a system | No type arguments | [EECS004](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs004); make the system generic | | Spans mixed with per-entity parameters | No single value per run | [EECS009](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs009) | | A parallel method that changes structure or writes a singleton | Races between chunks | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) | | Writing a collection through an `in` parameter | Scheduled as a read, never stamped | [EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) | | A structural change through a component's link in a method without `Entity` / `World` | The pass keeps refs into moved rows | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | | `UpdateInterval` that changes | Skipped or repeated runs | [EECS018](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs018) | | Orderings in a cycle, or across groups | Throws on `AddSystem`; never applies | [EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019), [EECS020](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs020) | | A private type in a method's parameters | The generated job cannot name it | [EECS022](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs022) | | `[With]`, `[Without]` or `[WithAny]` on a struct that is not a group | Compile error: the filter would do nothing | [EECS023](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs023) | | A group's `[With]` or `IGroupWith` with a method's `[Removed]` | Asks for rows that have and lack `T`: the method never runs | [EECS016](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs016) | | A group's `[With]` with a method's `[Without]` | No entity matches: the method never runs | Nothing reports it: code review | | A group's `[WithAny]` with a method's `[WithAny]`, read as "A and B" | The sets merge: entities with `A` or `B` | Code review | | A public `Key => this` on a record struct actor key | `ToString()` prints `Key` forever: stack overflow | Code review: implement `IIndexed.Key` explicitly | | `ref` on a component the method only reads | Stamps a tracked component, keeps the system out of shared stages | [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) | | An `Entity` or `World` parameter the method never uses | The job keeps its structural bookkeeping | [EECS026](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs026) | | An allocation in `OnUpdate` or a `[ForEach]` method | Garbage every update | [EECS028](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs028) | | An instance `[ForEach]` method that uses nothing of its system | Treated as one that may change structure: runs alone, with per-row checks | [EECS029](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs029) | | `World.Update()` called from a system | The system runs again inside its own run | [EECS034](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs034) | ## Related - [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries): The same filters, and struct jobs for ad-hoc passes. - [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes): Creating, destroying, adding and removing inside a `[ForEach]` method. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): Parallel stages, one world per thread, input from other threads. - [Analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer): Every rule a system has to follow, with its fix. --- # 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. URL: https://ecs.xgamedev.net/en/docs/guide/singletons Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/singletons.md Some state belongs to the whole world, not to an entity: the tick clock, the match configuration, a score, a spatial grid. A singleton is a struct that implements `ISingletonComponent`, with exactly one value per world. It is where world-level state goes, since systems keep none ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007)), and because it lives in the world, two worlds on two threads never share it. ## When to use it > **Use it for** > > World-level state that systems read or write: the clock and delta time, configuration loaded at startup, counters > and totals, a spatial grid or a lookup table, the queue of input a system drains each tick. > **Skip it for** > > Static fields: every world in the process would share them. Per-entity data: that is a component. A list of things > that each have their own state (players in a match): those are entities with a tag, which queries and indexes can > select. ## How to use it ### Declare it ```csharp public record struct Clock(long Tick, float DeltaTime) : ISingletonComponent; public record struct Score(int Deaths) : ISingletonComponent; ``` ### Add, read and write ```csharp var world = new World(); world.SetClock(0, 1f / 30); // generated: adds it, or overwrites it world.Clock.Tick++; // generated: a ref, throws if not added ref var score = ref world.GetOrAddScore(); // adds a default value if missing score.Deaths++; ``` ### Take it in a system A `[ForEach]` method takes a singleton as a `ref` or `in` parameter. It is resolved once per pass, not once per entity. The singleton must exist by then: a system whose singleton was never added throws `InvalidOperationException` on its first run, even when no entity matches, so add it where the world is built. ```csharp public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp, ref Score score) { if (hp.Value > 0) return; unit.SetDead(); score.Deaths++; } } public class ClockSystem : EcsSystem { protected override void OnUpdate() => World.Clock.Tick++; // in OnUpdate: through the system's World } ``` ### The API | Call | Generated member | Effect | | ----------------------------------- | --------------------------------- | --------------------------------------------------------------------------------------------------------------- | | `ref T AddSingleton()` | | Adds it, or resets an existing one to `default` in place | | `ref T GetSingleton()` | `world.Clock` | A ref; throws if it was not added | | `ref T GetOrAddSingleton()` | `world.GetOrAddClock()` | A ref, adding `default` first if missing | | `GetOrAddSingleton() = value` | `world.SetClock(tick, deltaTime)` | Sets the value, adding it if missing | | `bool HasSingleton()` | `world.HasClock` | Whether it exists | | `bool TryGetSingleton(out T)` | | A copy, if present | | `bool RemoveSingleton()` | `world.RemoveClock()` | Removes it; false if it was not added | | `SingletonRef SingletonRef()` | | A [stable handle](https://ecs.xgamedev.net/en/docs/guide/singletons#stable-handles); throws if it was not added | ```csharp world.SetScore(0); // generated from the record's constructor bool has = world.HasClock; if (world.TryGetSingleton(out var copy)) Console.WriteLine(copy.Tick); world.RemoveScore(); ``` The generated members follow the rules of [generated members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members): `SetX` has one overload per public constructor, and a singleton without fields gets no `GetOrAddX`. ### Stable handles A singleton's storage never moves, unlike component rows. `world.SingletonRef()` returns a `SingletonRef` (it throws if the singleton was not added) whose `Value` is a `ref T` with no lookup at all, valid for as long as the singleton exists. Take it once at setup and keep it, in a field of your host or a local of a loop. ```csharp var clock = world.SingletonRef(); // once, at setup clock.Value.Tick++; // later: a ref, no lookup ``` - `AddSingleton()` on an existing singleton resets it in place, so the handle sees the reset value. - `RemoveSingleton()` detaches it: writes through the old handle no longer reach the world, also after the singleton is added again. Take a new handle then. - [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots) restore singletons into the same storage, so handles keep working after a `Restore`. - Generated `[ForEach]` jobs resolve each singleton parameter once per pass; parallel jobs, which are copied to other threads, carry a `SingletonRef`. ### Singletons and threads - A singleton belongs to its world, so one world per thread shares nothing. - With `WorldOptions.ParallelSystems`, a system that takes a singleton by `ref` writes it: it never shares a stage with another system that reads or writes the same singleton. Take it by `in` when the system only reads it. - A `[ForEach(Parallel = true)]` method takes singletons only by `in`: every chunk would race on a `ref` ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010)). - A singleton that holds a collection (a grid of cells, a queue) and is changed through an `in` parameter is scheduled as a read: [EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) asks for `ref`. ## Full example A clock, a configuration and a score as singletons: poison hurts three units each tick, and the death system counts the dead. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Health(int Value) : IComponent; public struct Dead : IComponent; // World-level state: one value per world. public record struct Clock(long Tick) : ISingletonComponent; public record struct Poison(int DamagePerTick) : ISingletonComponent; public record struct Score(int Deaths) : ISingletonComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Advances the clock once per update, through the system's World. public class ClockSystem : EcsSystem { protected override void OnUpdate() { World.Clock.Tick++; } } // Reads the configuration by `in`: resolved once per pass, not once per unit. [UpdateAfter] public class PoisonSystem : EcsSystem { [ForEach, Without] static void Hurt(ref Health hp, in Poison poison) { hp.Value -= poison.DamagePerTick; } } // Writes the score by `ref`, reads the clock by `in`. [UpdateAfter] public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp, ref Score score, in Clock clock) { if (hp.Value > 0) { return; } unit.SetDead(); score.Deaths++; Console.WriteLine($" tick {clock.Tick}: {unit} dies"); } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); // Add the singletons where the world is built: // a system that takes one throws on its first run otherwise. world.SetClock(0); world.SetPoison(25); world.SetScore(0); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.CreateEntity(new Health(50)); world.CreateEntity(new Health(75)); world.CreateEntity(new Health(100)); // A handle the host keeps: its Value is a ref, with no lookup. var score = world.SingletonRef(); for (int i = 0; i < 2; i++) { world.Update(); } Console.WriteLine($"after tick {world.Clock.Tick}: {score.Value.Deaths} dead"); // Configuration changed from outside: the next pass reads the new value. world.Poison.DamagePerTick = 50; world.Update(); Console.WriteLine($"after tick {world.Clock.Tick}: {score.Value.Deaths} dead"); ``` It prints: ```text tick 2: Entity 0v1 dies after tick 2: 1 dead tick 3: Entity 2v1 dies tick 3: Entity 1v1 dies after tick 3: 3 dead ``` The host reads the score through the `SingletonRef` it took once, and the systems see the configuration it changes on the next update: with the poison doubled, both remaining units die on tick 3. ## How to use it fast | Instead of | Do | Why | | ----------------------------------------------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `GetSingleton()` (or `World.X`) per entity inside a loop | A singleton parameter of the `[ForEach]` method | Resolved once per pass ([EECS027](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs027) in a `[ForEach]` method) | | A lookup on every call from host code | A `SingletonRef` kept from setup | No lookup | | `ref` for a singleton the system only reads | `in` | Lets the system share a parallel stage ([EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025)) | | A static field | A singleton | Per world, saved and snapshotted with it | 1,000 singleton reads and writes through `GetSingleton()`, next to 1,000 component writes through entity handles (`MicroBenchmarks`): | Case | Mean | vs baseline | Allocated | | --------------- | ------- | ----------- | --------- | | SingletonAccess | 1.01 μs | 0.08× | 0 B | | HandleAccess | 3.33 μs | 0.26× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. A pass that writes a singleton for each of 100,000 entities, against Friflo.Engine.ECS: **A pass that writes a singleton, 100,000 entities** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | --------- | ------ | ---------- | --------- | | EasyEcs | Singleton | 212 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Singleton | 222 μs | 1.05× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Storage:** one small box per singleton type in each world that has it; nothing per entity. - **`GetSingleton`, `HasSingleton`:** a bounds check, one array load and a null check, with no type check; O(1). - **`SingletonRef.Value`:** one field load. - **A `[ForEach]` parameter:** resolved once per pass. - **Adding or removing** a singleton goes through the world's structural gate, like any structural change. ## Pitfalls | Mistake | What happens | Caught by | | ------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | State kept in a system field instead | Invisible to other systems, lost on remove, shared by worlds if static | [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007) | | A class implementing `ISingletonComponent` | Does not compile | [EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006) | | Reading a singleton before it was added (`world.X`, `GetSingleton()`, a `[ForEach]` parameter) | `InvalidOperationException`, naming the call that adds it | Add it at setup, or use `GetOrAddX()` where the default is right | | A `ref` singleton in a parallel method | Races between chunks | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) | | `AddSingleton` or `RemoveSingleton` in a batch method, a parallel method or a parallel stage | `InvalidOperationException`: both go through the structural gate, and the structure is frozen there | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010), [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013), and at run time | | Changing a collection in a singleton through `in` | Scheduled as a read | [EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) | | Writing through a `SingletonRef` after `RemoveSingleton` | The write reaches nothing | Take a new handle after re-adding | | A list of players in a singleton | Duplicates what entities and queries give | Make them entities with a tag | ## Related - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): Singleton parameters, resolved once per pass. - [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles): Why systems are stateless and state is data. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): One world per thread and parallel stages. - [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots): Singletons are captured and restored with the world. --- # 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. URL: https://ecs.xgamedev.net/en/docs/guide/structural-changes Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/structural-changes.md 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. ```csharp 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] 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 ```csharp var world = new World(); world.AddSystem(); world.AddSystem(); // sees this update's new projectiles world.CreateEntity(new Position(0, 0), new Weapon(0)); world.Update(); int shots = world.Count(); // 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. ```mermaid flowchart LR A["pass reaches a row"] --> B{"still matches?"} B -- no --> C["skip"] B -- yes --> D["call the method"] D --> E["changes apply now"] E --> F["next row"] C --> F ``` ### 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()`, 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`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity): 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. ```csharp public class HitSystem : EcsSystem { [ForEach, Without] 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`](https://ecs.xgamedev.net/en/docs/guide/refs-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` 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](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems). The analyzer reports a structural change in a method that promised none ([EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013)) and one made from another thread ([EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#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: ```csharp var wave = new Entity[1_000]; world.CreateEntities(wave, new Position(0, 0), new Lifetime(60)); int expired = world.DestroyEntities(QueryFilter.Create().With()); ``` `SetAll`, `RemoveAll`, `DisableAll` and `EnableAll` change a component on every match a whole 64-row word at a time: [Bulk changes](https://ecs.xgamedev.net/en/docs/guide/bulk). 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(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: ```csharp world.EnsureCapacity(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](https://ecs.xgamedev.net/en/docs/guide/prefabs)), and `EnsureEntityCapacity(n)` sizes only the entity storage, for entities spread over many tables. Entities that a [group](https://ecs.xgamedev.net/en/docs/guide/groups) 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`. **Components.cs** ```csharp using EasyEcs; // A turret: a weapon on a cooldown, and health that wears down every tick. public record struct Weapon(int Cooldown) : IComponent; public record struct Health(int Value) : IComponent; // A shot: who fired it, and how many ticks it has left. public record struct Projectile(EntityId Owner) : IComponent; public record struct Lifetime(int Ticks) : IComponent; // A tag: the turret is out of health. public struct Dead : IComponent; ``` **Systems.cs** ```csharp using EasyEcs; // The turret loses 30 health a tick, and is tagged Dead where that is decided. public class WearSystem : EcsSystem { [ForEach, Without] static void Wear(Entity turret, ref Health hp) { hp.Value -= 30; if (hp.Value <= 0) { // The row moves to the table with Dead, now. turret.SetDead(); // hp is still this turret's Health: the write is carried to its new row. hp.Value = 0; Console.WriteLine($" {turret} is dead"); } } } // Fires every other tick. A turret tagged Dead earlier in this update no longer matches. [UpdateAfter] public class FireSystem : EcsSystem { [ForEach, Without] static void Fire(Entity turret, ref Weapon weapon, World world) { if (weapon.Cooldown > 0) { weapon.Cooldown--; return; } weapon.Cooldown = 1; var shot = world.CreateEntity(new Projectile(turret.Id), new Lifetime(3)); Console.WriteLine($" {turret} fires {shot}"); } } // Counts down every shot, including the ones fired earlier in this update, // and destroys a shot in the middle of its own pass. [UpdateAfter] public class ExpireSystem : EcsSystem { [ForEach] static void Expire(Entity shot, ref Lifetime life) { life.Ticks--; if (life.Ticks == 0) { Console.WriteLine($" {shot} expires"); shot.Destroy(); } } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); world.AddSystem(); world.AddSystem(); world.AddSystem(); var turret = world.CreateEntity(new Weapon(0), new Health(100)); for (int tick = 1; tick <= 5; tick++) { Console.WriteLine($"tick {tick}"); world.Update(); int shots = world.Count(); Console.WriteLine($" hp {turret.Health.Value}, shots in flight {shots}"); } ``` It prints: ```text 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 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(count)` before the loop | One growth instead of a doubling per full table ([EECS031](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs031)) | | A loop of single changes over a filter | [Bulk changes](https://ecs.xgamedev.net/en/docs/guide/bulk), `DestroyEntities(filter)` | One gate pass, whole 64-row words at once ([EECS030](https://ecs.xgamedev.net/en/docs/guide/analyzer#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 | 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** | 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 | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The comparison with 10 changes per pass: [Comparison](https://ecs.xgamedev.net/en/docs/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](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | | A change in a batch method | `InvalidOperationException`: the spans point into the tables | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013), and at run time | | A change in a parallel method | `InvalidOperationException`: the structure is frozen while chunks run | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010), and at run time | | A change from another thread | Races with the owner thread | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) | | `INoStructuralChanges` on a job that changes structure | `InvalidOperationException` at the change | At run time | | A `ref` from `Get()` 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](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs034) | | `Update()` while a query of the same world iterates | Undefined order of passes | Code review | ## Related - [ref and await](https://ecs.xgamedev.net/en/docs/guide/refs-and-await): Which refs survive a change, and why none survives an `await`. - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): Which methods may change structure, and which run frozen. - [Bulk changes](https://ecs.xgamedev.net/en/docs/guide/bulk): Change a component on every match at once. - [Architecture](https://ecs.xgamedev.net/en/docs/architecture): How passes, tombstones and storage versions work inside. --- # 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. URL: https://ecs.xgamedev.net/en/docs/guide/bulk Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/bulk.md A round ends and every fighter is stunned; the stun lifts from everyone; a zone freezes; a wave of monsters spawns and is later cleared. Written entity by entity, each of these is a loop of structural changes. `SetAll`, `RemoveAll`, `DisableAll` and `EnableAll` change one component on every entity a filter selects in one pass through the structural gate, a whole 64-row word at a time where they can, with the same results as the loop: tracked components count as written, indexes and groups follow. ## When to use it > **Use it for** > > The same change on many entities at once: round resets, a status applied to or lifted from a whole team or zone, > pausing a component everywhere (`DisableAll`), spawning and clearing waves (`CreateEntities`, `DestroyEntities`). > **Skip it for** > > Changes whose value depends on each entity (damage from each unit's armor): that is a `[ForEach]` system writing > through `ref`. A handful of entities you already hold: `Set` on each is as fast. ## How to use it ### Set and remove on every match `SetAll(value, filter)` gives every matching entity the component, added or replaced; `RemoveAll(filter)` removes it from every match that has it. Both return how many entities they changed. ```csharp public record struct Fighter(int Team) : IComponent; public record struct Stun(int Ticks) : IComponent; public static class Rounds { public static readonly QueryFilter Fighters = QueryFilter.Create().With(); } ``` ```csharp var fighters = new Entity[1_000]; world.CreateEntities(fighters, new Fighter(1), new Health(100)); int stunned = world.SetAll(new Stun(3), Rounds.Fighters); // the round ends: everyone is stunned int lifted = world.RemoveAll(); // the stun lifts from everyone ``` Without a filter, `RemoveAll()` takes `T` from every entity that has it, and `SetAll` gives it to every alive entity, so name what to select (`With()`). Any `QueryFilter` works, including `Without`, `WithAny`, `Changed` and [`InGroup`](https://ecs.xgamedev.net/en/docs/guide/groups). ### Disable and enable on every match `DisableAll(filter)` and `EnableAll(filter)` are [`Disable()` and `Enable()`](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable#disable-a-component) on every match: values are kept and given back. ```csharp int paused = world.DisableAll(Rounds.Fighters); // nobody regenerates during the cutscene int resumed = world.EnableAll(); // every kept value comes back ``` ### Spawn and clear waves The structural counterparts for whole entities create a wave with one set of values and destroy every match: ```csharp public record struct Shot(int Damage) : IComponent; ``` ```csharp var volley = new Entity[10_000]; world.CreateEntities(volley, new Shot(5), new Position(0, 0)); // one table, rows placed at once int cleared = world.DestroyEntities(); // every shot, in one pass ``` `world.Instantiate(prefab, span)` spawns a wave from a [prefab](https://ecs.xgamedev.net/en/docs/guide/prefabs). ### What the bulk calls keep | | `SetAll` | `RemoveAll` | `DisableAll` | `EnableAll` | | --------------------------------------------------------------------------------------------------- | ------------------------------------- | ----------------------------------- | ----------------- | --------------- | | [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking) | a write per row | a removal per row (tracked `T`) | a removal per row | a write per row | | [Indexes](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) | re-indexed | unlinked | unlinked | re-linked | | [Groups](https://ecs.xgamedev.net/en/docs/guide/groups) | moved to the value's group | | | | | On a disabled `T` | replaced: enabled, with the new value | | | | | [Cleanup components](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable#cleanup-components) | | the last one frees a retired entity | refused (throws) | | All four are structural changes of the owner thread: call them between updates, from a system's `OnUpdate`, or from a `[ForEach]` method that takes an `Entity` or the `World` (a method that takes neither promises no structural change). ## Full example A round of a fight: 1,000 fighters are stunned and released, their regeneration paused for a cutscene and resumed, then a volley of shots is spawned and cleared, each with one call. A system heals the fighters that are neither stunned nor paused. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Fighter(int Team) : IComponent; public record struct Health(int Value) : IComponent; // Health regained per update. A cutscene pauses it with DisableAll. public record struct Regen(int PerTick) : IComponent; // A stunned fighter does not regenerate. public record struct Stun(int Ticks) : IComponent; public record struct Shot(int Damage) : IComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Fighters that are not stunned regain health. A disabled Regen is hidden, so it pauses too. public class RegenerateSystem : EcsSystem { [ForEach, Without] static void Heal(ref Health health, in Regen regen) { health.Value += regen.PerTick; } } ``` **Filters.cs** ```csharp using EasyEcs; public static class Rounds { // Filters are values: build them once and keep them in fields. public static readonly QueryFilter Fighters = QueryFilter.Create().With(); } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); world.AddSystem(); // One call creates the whole roster in one table. var fighters = new Entity[1_000]; world.CreateEntities(fighters, new Fighter(1), new Health(100), new Regen(2)); Entity first = fighters[0]; // The round ends: every fighter is stunned, in one pass. int stunned = world.SetAll(new Stun(3), Rounds.Fighters); world.Update(); Console.WriteLine($"stunned {stunned}: health {first.Health.Value}"); // The stun lifts from everyone. int lifted = world.RemoveAll(Rounds.Fighters); world.Update(); Console.WriteLine($"lifted {lifted}: health {first.Health.Value}"); // A cutscene: regeneration pauses everywhere and keeps its values. int paused = world.DisableAll(Rounds.Fighters); world.Update(); Console.WriteLine($"paused {paused}: health {first.Health.Value}"); // The cutscene ends: every kept value comes back. int resumed = world.EnableAll(Rounds.Fighters); world.Update(); Console.WriteLine($"resumed {resumed}: health {first.Health.Value}"); // SetAll on a disabled component replaces it: enabled again, with the new value. world.DisableAll(Rounds.Fighters); world.SetAll(new Regen(5), Rounds.Fighters); world.Update(); int stillPaused = world.Count>(); Console.WriteLine($"set while paused: health {first.Health.Value}, still paused {stillPaused}"); // A volley is spawned in one call and cleared in one pass. var volley = new Entity[10_000]; world.CreateEntities(volley, new Shot(5)); int cleared = world.DestroyEntities(); Console.WriteLine($"shots cleared: {cleared}, entities left: {world.EntityCount}"); ``` It prints: ```text stunned 1000: health 100 lifted 1000: health 102 paused 1000: health 102 resumed 1000: health 104 set while paused: health 109, still paused 0 shots cleared: 10000, entities left: 1000 ``` The stunned update heals nobody (100), the paused one neither (102 stays 102). `SetAll` on the paused `Regen` gives it back with the new value at once: the next update heals 5, and no `Disabled` is left. ## How to use it fast - **Let the column stay.** After the first round, the stun's column stays in the fighters' table: `SetAll` and `RemoveAll` then flip presence bits, 64 rows per word, and no row moves. - **Keep the filter in a `static readonly` field**, like any hot filter. - **One call instead of a loop.** The bulk call enters the structural gate once and works table by table. A round reset of 100,000 fighters (stun everyone, lift it) and a status disabled and enabled for all of them, in bulk and entity by entity (`BulkBenchmark`): | Case | Mean | vs baseline | Allocated | | -------------------- | ------- | ----------- | --------- | | StunAndLift | 87.9 μs | 1.00× | 0 B | | StunAndLiftEach | 1.68 ms | 19× | 0 B | | DisableAndEnable | 22.9 μs | 0.26× | 0 B | | DisableAndEnableEach | 2.27 ms | 26× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Time:** O(matching tables + rows). Rows that already have the column are a presence-bit flip; an entity that lacks the column moves once, to the table that has it. - **Allocation:** 0 B once the target tables exist. - **`SetAll` counts first:** a moved row can be visited again in its new table, so the count is taken before the change. ## Pitfalls | Mistake | What happens | Caught by | | ------------------------------------------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | A bulk call inside a `[ForEach]` method without `Entity` or `World` | A structural change the pass did not plan for | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | | A bulk call from another thread | Races with the owner thread | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) | | `DisableAll` of a cleanup component or `ChildOf` | `InvalidOperationException` | At run time | | `SetAll` with a value that should differ per entity | Every entity gets the same value | Use a `[ForEach]` system | | `Set` / `Remove` entity by entity over a query | The same result, one structural change per entity | [EECS030](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs030) | | `CreateEntity` or `Instantiate(prefab)` in a counted loop | One creation per entity instead of one per wave | [EECS031](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs031): `CreateEntities`, `Instantiate(prefab, span)` | ## Compared with other libraries Friflo applies an `EntityBatch` to a query's entities, Arch adds or removes by query (whole tables move), and DefaultEcs changes entities one by one. The same round reset of 100,000 fighters: **Stun 100,000 fighters, then lift the stun from everyone** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | ------- | ---------- | --------- | | EasyEcs | SetAllRemoveAll | 78.7 μs | 1.00× | 0 B | | Friflo.Engine.ECS | ApplyBatch | 12.1 ms | 154× | 4.00 MB | | Arch | AddRemoveByQuery | 1.21 ms | 15× | 0 B | | DefaultEcs | PerEntity | 8.12 ms | 103× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. And a volley of 10,000 shots spawned beside 100,000 fighters, then cleared: **Spawn 10,000 shots, then destroy them all** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------------------- | ------- | ---------- | --------- | | EasyEcs | CreateAndDestroyAll | 138 μs | 1.00× | 0 B | | Friflo.Engine.ECS | PerEntity | 380 μs | 2.75× | 0 B | | Arch | CreateAndDestroyByQuery | 409 μs | 2.96× | 0 B | | DefaultEcs | PerEntity | 1.33 ms | 9.7× | 313 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Related - [Cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable): `Disable()` on one entity, cleanup components. - [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes): What a structural change is, and when it applies. - [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries): The `QueryFilter` every bulk call takes. --- # Cleanup and disable > Release outside resources exactly once with ICleanupComponent, pause a component with Disable and switch whole entities off in a C# ECS. URL: https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/cleanup-and-disable.md Four lifecycle needs of a server, each solved with data. A session that holds a socket must close it once, even when the session is destroyed in a bulk call: a **cleanup component** keeps the entity until a system releases it. A cooldown paused by a stun must keep its value: **`Disable()`** hides a component and keeps it. A pooled bullet must leave every system without being destroyed: a **tag** with `Without` switches the whole entity off. And a system that greets new players needs to tell them apart: a **`Spawned` tag** marks them. ## When to use it > **Use it for** > > Cleanup components: anything outside the world released exactly once (sockets, seats, leases, file handles, a slot > in another service). `Disable()`: a component paused for a while with its value kept (a cooldown under a stun, an > AI behaviour while a cutscene runs). A tag: whole entities parked (pools, sleeping zones, players reconnecting). > **Skip it for** > > Cleanup components for state the world owns: destroying the entity already frees it. `Disable()` for a state you > can express as a tag the systems read: a tag is clearer. Whole-entity disable "by default" does not exist on purpose: > see [Disabling a whole entity](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable#disable-an-entity). ## How to use it ### Cleanup components An entity destroyed while it holds an `ICleanupComponent` is not freed. It loses every other component, gets the `Destroyed` tag, and stays alive until its last cleanup component is removed: ```csharp public record struct Seat(int Number) : ICleanupComponent; // a resource outside the world public record struct Seats(int Released) : ISingletonComponent; ``` ```csharp public class ReleaseSeats : EcsSystem { [ForEach, With, With] // only entities already destroyed static void Release(Entity entity, ref Seats seats) { seats.Released++; // give the seat back here entity.RemoveSeat(); // the last cleanup component: the entity is freed } } ``` ```csharp world.AddSingleton(); world.AddSystem(); var guest = world.CreateEntity(new Seat(7), new Health(10)); guest.Destroy(); // alive, tagged Destroyed, Health gone world.Update(); // ReleaseSeats frees it: guest.IsAlive is false ``` - Every destroy path retires such entities: `Destroy`, `DestroyEntities()`, a [hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy) cascade or a [target policy](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#target-policies). - A system that acquires the resource filters `Without`: a retired entity still holds its cleanup component, so without the filter it could acquire again after it left: ```csharp public record struct NextSeat(int Number) : ISingletonComponent; public class AssignSeats : EcsSystem { [ForEach, Without] // never seat an entity that already left static void Assign(ref Seat seat, ref NextSeat next) { if (seat.Number != 0) return; // already seated next.Number++; seat = new Seat(next.Number); // take the seat here } } ``` - Destroying a retired entity again does nothing. Removing a cleanup component from a live entity just removes it. - A retired entity leaves its indexes, and its children go with it. - A cleanup component cannot be disabled (`Disable()` throws): it must stay to be released. ### Disabling a component `Disable()` keeps the value of `T` but hides it: queries, `Has` and `Get` act as if the entity lacked `T`, until `Enable()` gives it back. The entity gets the tag `Disabled`, which you can query. ```csharp public record struct Cooldown(int Ticks) : IComponent; public class TickCooldowns : EcsSystem { [ForEach] static void Tick(ref Cooldown cooldown) => cooldown.Ticks--; } ``` ```csharp world.AddSystem(); var caster = world.CreateEntity(new Cooldown(3)); caster.DisableCooldown(); // stunned: the cooldown is paused, its value kept world.Update(); // TickCooldowns skips it bool paused = caster.IsCooldownDisabled; int stunnedCasters = world.Count>(); caster.EnableCooldown(); // back with Ticks = 3 ``` | Call | Effect | | ------------------------------------------------------ | ------------------------------------------------------------------------------- | | `DisableX()` (generated) / `Disable()` | Hides `T`, keeps its value, adds `Disabled`. False if the entity lacks `T` | | `EnableX()` (generated) / `Enable()` | Gives the kept value back. False if `T` is not disabled | | `IsXDisabled` (generated) / `IsDisabled()` | Whether the entity has `Disabled` | | `Set(new T(...))` on a disabled `T` | Replaces it: enabled, with the new value | | `Remove()` on a disabled `T` | Drops it: nothing left to enable | | `world.DisableAll(filter)` / `EnableAll(filter)` | The same on every match, in [bulk](https://ecs.xgamedev.net/en/docs/guide/bulk) | A disable counts as a removal for `[Removed]`, and an enable as a write for `[Changed]`, so [replication](https://ecs.xgamedev.net/en/docs/guide/change-tracking#removal-detection) sees both. An indexed component leaves its index while disabled. The kept value survives moves, clones, snapshots and saves. ### Disabling a whole entity There is no "disabled entity" that queries skip by default. A tag and `Without` do it, and say so where it matters: ```csharp public struct Inactive : IComponent; // the whole entity is off public struct Bullet : IComponent; public class MoveBullets : EcsSystem { [ForEach, Without] // 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); } ``` ```csharp var bullet = world.CreateEntity(new Position(0, 0), new Velocity(1, 0), new Bullet()); bullet.SetInactive(); // back to the pool: after the first time, a bit flip bullet.SetPosition(5, 5).RemoveInactive(); // reused int pooled = world.Count(QueryFilter.Create().With()); // saves, cleanup and stats see everything ``` Why a tag ([decision D8](https://ecs.xgamedev.net/en/docs/decisions#d8-no-whole-entity-disable)): 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 would have to opt back in, and forgetting it fails silently. The tag is data the generator and the reader both see. | | Friflo.Engine.ECS | DefaultEcs | EasyEcs | | -------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------- | | How | `entity.Enabled = false`: a hidden tag, queries skip it unless `WithDisabled()` | `entity.Disable()`: the entity leaves every entity set | A tag of yours and `Without` | | Switching off or on | Moves the 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; a test per 64 rows when mixed | The measured cost, with 100 units switching per operation (most stay as they are) and with 10,000 (frequent switching), then the awake units summed (`DisableComparison`): **100,000 units, 100 fall asleep and wake per operation** | 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 | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **100,000 units, 10,000 fall asleep and wake per operation** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | ------- | ---------- | --------- | | EasyEcs | Tag | 478 μs | 1.00× | 0 B | | EasyEcs | DisableComponent | 563 μs | 1.18× | 0 B | | Friflo.Engine.ECS | Enabled | 797 μs | 1.67× | 0 B | | Arch | Tag | 1.26 ms | 2.63× | 0 B | | DefaultEcs | Disable | 745 μs | 1.56× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Pools and effects switch often, where a bit flip beats a row move. When many entities stay off for long, mixed with awake ones in one table, [`GroupBy`](https://ecs.xgamedev.net/en/docs/guide/groups) on a sleeping state puts them in tables of their own. ### Telling new entities apart: the `Spawned` tag There is no `Added` filter. `[Changed]` already selects rows that gained `T` (adding stamps the tick, as a write does). When a system must tell a new entity from a written one, the creator adds a tag and the reacting system removes it ([decision D4](https://ecs.xgamedev.net/en/docs/decisions#d4-no-addedt-filter)): ```csharp public struct Spawned : IComponent; public record struct Greeted(int Count) : ISingletonComponent; public class GreetNewcomers : EcsSystem { [ForEach, With, With] static void Greet(Entity entity, ref Greeted greeted) { greeted.Count++; // first-time work entity.RemoveSpawned(); // a bit flip: greeted once } } ``` ```csharp world.AddSingleton(); world.AddSystem(); world.CreateEntity(new Health(100), new Spawned()); // the creator says it is new world.Update(); ``` The tag is explicit, queryable, saved with the world and costs one presence bit flip. ## Full example A player holds a seat at a table, a resource outside the world, and a cooldown that is paused while it is stunned. When the player leaves, a system gives the seat back before the entity is freed. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; // A cleanup component: an entity destroyed while holding it stays until a system removes it. public record struct Seat(int Number) : ICleanupComponent; public record struct Cooldown(int Ticks) : IComponent; // How many seats were given back. public record struct Seats(int Released) : ISingletonComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Counts every cooldown down. A disabled cooldown is hidden from this method, so it is paused. public class CooldownSystem : EcsSystem { [ForEach] static void Tick(ref Cooldown cooldown) { if (cooldown.Ticks > 0) { cooldown.Ticks--; } } } // Gives back the seats of destroyed players. Removing the last cleanup component frees the entity. public class ReleaseSeatsSystem : EcsSystem { [ForEach, With, With] static void Release(Entity player, ref Seats seats) { seats.Released++; player.RemoveSeat(); } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); world.AddSingleton(); world.AddSystem(); world.AddSystem(); Entity player = world.CreateEntity(new Seat(7), new Cooldown(3)); // Stunned: the cooldown is hidden from queries and keeps its value. player.DisableCooldown(); world.Update(); int stunned = world.Count>(); Console.WriteLine($"stunned: has cooldown {player.HasCooldown}, stunned players {stunned}"); // Back: the kept value returns, and the paused update did not count. player.EnableCooldown(); world.Update(); Console.WriteLine($"resumed: {player.Cooldown.Ticks} ticks left"); // The player leaves. It keeps its seat and gets the Destroyed tag; everything else goes. player.Destroy(); Console.WriteLine($"destroyed: alive {player.IsAlive}, tagged {player.Has()}"); world.Update(); int released = world.Seats.Released; Console.WriteLine($"after the update: alive {player.IsAlive}, seats released {released}"); ``` It prints: ```text stunned: has cooldown False, stunned players 1 resumed: 2 ticks left destroyed: alive True, tagged True after the update: alive False, seats released 1 ``` The cooldown went from 3 to 2: the update during the stun skipped it. Between `Destroy` and the next update the player is still alive, but only `ReleaseSeatsSystem` sees it, because it asks for `Destroyed`. ## How to use it fast | Instead of | Do | Why | | ------------------------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------- | | Releasing a resource in every place that destroys | A cleanup component and one system | One release path, also for bulk destroys and cascades | | Removing and re-adding a component to pause it | `Disable()` / `Enable()` | The value stays; `Set` would need it stored elsewhere | | A loop of `Disable` over many entities | `world.DisableAll(filter)` | 64 rows at a time, one word of presence bits ([bulk](https://ecs.xgamedev.net/en/docs/guide/bulk)) | | A flag field every system tests | A tag and `Without` | Tables without the tag skip the test entirely | 10,000 sessions with an outside resource, 1,000 disconnecting and 1,000 connecting per operation, with a cleanup component against a plain component released before the destroy (`CleanupBenchmark`); and 100,000 entities disabled and enabled in bulk and one by one (`BulkBenchmark`): | Case | Mean | vs baseline | Allocated | | ------- | ------- | ----------- | --------- | | Cleanup | 102 μs | 1.00× | 0 B | | Plain | 43.9 μs | 0.43× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | -------------------- | ------- | ----------- | --------- | | DisableAndEnable | 22.9 μs | 0.26× | 0 B | | DisableAndEnableEach | 2.27 ms | 26× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Cleanup components:** a retired entity keeps its id and a row with its cleanup components until released; a world without them pays nothing on destroy. - **`Disable()`:** O(1). The first disable in a table moves the row once, to the table with the `Disabled` column; after that a disable or enable flips presence bits. - **A tag:** one presence bit per row; a flip after the first time. Tables with no `Inactive` row skip the test. - **`Spawned`:** a tag like any other: a bit flip to add, a bit flip to remove. ## Pitfalls | Mistake | What happens | Caught by | | ----------------------------------------------------------- | ---------------------------------------------------------------------------- | ---------------------------------------- | | A cleanup system without `With` | It releases resources of live entities | Code review | | Never removing the last cleanup component | The retired entity stays forever | `world.Count()` in your stats | | `Disable()` on a cleanup component or `ChildOf` | `InvalidOperationException` | At run time | | `Set` on a disabled component expecting it to stay disabled | `Set` enables it with the new value; use `Enable` to get the kept value back | By design | | Forgetting `Without` on a system | Pooled entities keep moving | Code review | | Expecting `[Changed]` to tell new from written | Both are writes | Use a `Spawned` tag | ## Related - [Bulk changes](https://ecs.xgamedev.net/en/docs/guide/bulk): `DisableAll`, `EnableAll`, `SetAll`, `RemoveAll`. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): Disabling counts as a removal, enabling as a write. - [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy): Cascades retire children that hold cleanup components. --- # ref and await > Change components through a ref. Which refs survive a structural change, why none may cross an await, and how async code reaches the world safely. URL: https://ecs.xgamedev.net/en/docs/guide/refs-and-await Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/refs-and-await.md Components are structs stored in the columns of tables. `entity.Get()` returns a `ref` into that column: changing it changes the entity, with no copy and no second lookup. A copy changes nothing. And because rows move when entities change, a `ref` is valid only until the next structural change, so it never crosses an `await`: after one, you re-acquire the data through the `Entity` handle, which tells you whether the entity is still there. ## When to use it > **Use it for** > > Every write of a component: `ref var hp = ref unit.Get()`, the generated `unit.Health.Value -= 10`, `ref` > parameters of `[ForEach]` methods. Short-lived refs inside one method, used before the next structural change. > **Skip it for** > > Keeping data across time: a `ref` in a field, across an `await`, or across a structural change. Keep the `Entity` > (or its `EntityId`) instead and look the data up again. Reading a tracked component: use `Read()` or the > generated property, so the read is not stamped as a write. ## How to use it ### Copies and refs ```csharp var copy = entity.Health; // a copy: the change below is lost copy.Value -= 10; ref var hp = ref entity.Health; // a ref into the table hp.Value -= 10; entity.Health.Value -= 10; // the same, inline entity.Get().Value -= 10; // the same, through the generic API ``` ### Why a `ref` expires A `ref` into a table is valid only until the next structural change, of any entity: - an entity's row is copied to another table when it gains a component its table has no column for; - the last row of a table fills the row of an entity that left it; - a full table is reallocated when it grows. An old `ref` then silently points at a stale copy or at another entity's data. Which change moves which row is an implementation detail, and the change may come from your code or from another system, so treat every structural change as one that may invalidate your refs. ### Inside passes Use `ref` freely inside `[ForEach]` methods, `ForEach` jobs and `Query` loops: each entity gets fresh refs. - The **`ref` parameters of a `[ForEach]` method** (or a `ForEach` job) stay writable even when the body changes the archetype of the entity it visits: the pass copies those writes (for a job, the components in its `Writes`) to the entity's new row after the body returns. `in` parameters keep showing the values from before the change. - **A job run on one entity** with [`entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity) gets the same guarantee: its 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. - **Any other `ref`** (from `entity.Get()`, an item of a `Query` loop, or into another entity) is guaranteed only until the next structural change. Write through it before the change, or get it again afterwards. ```csharp public record struct Target(EntityId Id) : IComponent; public class StrikeSystem : EcsSystem { [ForEach, Without] static void Strike(Entity attacker, in Target target, World world) { if (!world.TryGetEntity(target.Id, out var victim) || !victim.HasHealth) return; ref var hp = ref victim.Health; hp.Value -= 10; // write first... if (hp.Value <= 0) victim.SetDead(); // ...then change structure: hp may now be stale attacker.RemoveTarget(); // structural too; refs taken before it are not used after it } } ``` ### Across `await` C# forbids a `ref` local that lives across an `await`; do not smuggle one through `Unsafe`, pointers or `Span` fields either. While you `await`, other code runs: it may add entities or components (moving and reallocating storage), or destroy your entity and recycle its index. So: 1. read what you need before awaiting; 2. after the await, re-validate through the `Entity` handle, which is version-checked; 3. write back through a newly acquired `ref`. ```csharp public record struct Account(long Id) : IComponent; public interface IShop { ValueTask RedeemPotionAsync(long accountId); } public static class Potions { // Runs on the world's owner thread, and resumes there (a single-threaded server loop). public static async ValueTask HealFromStoreAsync(Entity player, IShop shop) { long id = player.Account.Id; // read what you need before awaiting int heal = await shop.RedeemPotionAsync(id); // the world may change meanwhile if (player.IsAlive && player.HasHealth) // re-validate after the await player.Health.Value += heal; // a fresh ref into current storage } } ``` This is only correct when the code after the `await` runs on the world's owner thread, for example a server loop with its own single-threaded `SynchronizationContext`. If the continuation may resume on the thread pool, it must not touch the world at all: hand the result to the owner thread as data, and let a system apply it. ```csharp using System.Collections.Concurrent; public record struct PotionRedeemed(EntityId Player, int Heal); // a message, not a component // The queue is a dependency in a readonly field, which EECS007 allows. A managed queue in a singleton // would make World.Save need a formatter for it. public sealed class ApplyRedemptions(ConcurrentQueue inbox) : EcsSystem { private readonly ConcurrentQueue _inbox = inbox; // filled by async code on any thread protected override void OnUpdate() { while (_inbox.TryDequeue(out var done)) if (World.TryGetEntity(done.Player, out var player) && player.HasHealth) player.Health.Value += done.Heal; // on the owner thread, during the update } } ``` The system takes the queue through its constructor, so `AddSystem()` cannot create it: add an instance. The async side reads what it needs on the owner thread, then only enqueues: ```csharp var inbox = new ConcurrentQueue(); world.AddSystem(new ApplyRedemptions(inbox)); ``` ```csharp public static class PotionOrders { public static async ValueTask RedeemAsync( EntityId player, long accountId, IShop shop, ConcurrentQueue inbox) { int heal = await shop.RedeemPotionAsync(accountId); // may resume on any thread inbox.Enqueue(new PotionRedeemed(player, heal)); // data for the owner thread, nothing else } } ``` More on owner threads and input from other threads: [Threading](https://ecs.xgamedev.net/en/docs/guide/threading#input-from-other-threads). ### The exception: singletons A singleton's storage never moves, so `world.SingletonRef()` returns a handle you can keep, in a field of your host or across ticks ([Singletons](https://ecs.xgamedev.net/en/docs/guide/singletons#stable-handles)). It is still owner-thread data: keep it, but only touch it on the owner thread. ## Full example Two players redeem a potion from a remote shop. While the shop answers, one of them leaves and a new entity reuses his index; the system that applies the answers on the owner thread tells them apart by the `EntityId`'s version. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Health(int Value) : IComponent; public record struct Account(long Id) : IComponent; // A message from async code to the world, not a component. public record struct PotionRedeemed(EntityId Player, int Heal); ``` **Shop.cs** ```csharp // A remote store: it answers later, on a thread-pool thread. public interface IShop { ValueTask RedeemPotionAsync(long accountId); } public sealed class Shop : IShop { public async ValueTask RedeemPotionAsync(long accountId) { await Task.Delay(10); return 25; } } ``` **Redemptions.cs** ```csharp using System.Collections.Concurrent; using EasyEcs; public static class Redemptions { // Starts on the world's owner thread: reads what it needs before the first await. public static async Task RedeemAsync( Entity player, IShop shop, ConcurrentQueue inbox) { EntityId id = player.Id; long account = player.Account.Id; // Resumes on a thread-pool thread: from here on it must not touch the world. int heal = await shop.RedeemPotionAsync(account); inbox.Enqueue(new PotionRedeemed(id, heal)); } } ``` **Systems.cs** ```csharp using System.Collections.Concurrent; using EasyEcs; // Applies the redemptions on the owner thread, during the update. // The queue is a dependency in a readonly field (EECS007 allows it); a managed queue in a singleton // would make World.Save need a formatter for it. public sealed class ApplyRedemptions(ConcurrentQueue inbox) : EcsSystem { private readonly ConcurrentQueue _inbox = inbox; protected override void OnUpdate() { while (_inbox.TryDequeue(out var done)) { // The EntityId carries a version: a destroyed player fails here, // and so does a new entity on its index. if (World.TryGetEntity(done.Player, out var player) && player.HasHealth) { player.Health.Value += done.Heal; } else { Console.WriteLine($" dropped: {done.Player} is gone"); } } } } ``` **Program.cs** ```csharp using System.Collections.Concurrent; using EasyEcs; var inbox = new ConcurrentQueue(); var shop = new Shop(); using var world = new World(); // The system takes the queue through its constructor, so it is added as an instance. world.AddSystem(new ApplyRedemptions(inbox)); var alice = world.CreateEntity(new Health(40), new Account(1)); var bob = world.CreateEntity(new Health(60), new Account(2)); var orders = new[] { Redemptions.RedeemAsync(alice, shop, inbox), Redemptions.RedeemAsync(bob, shop, inbox), }; // While the shop works, Bob leaves, and a new entity reuses his index. bob.Destroy(); var carol = world.CreateEntity(new Health(10), new Account(3)); Console.WriteLine($"bob was {bob.Id}, carol is {carol.Id}"); // Waiting here only makes the output reproducible: a server keeps updating meanwhile. Task.WaitAll(orders); world.Update(); Console.WriteLine($"alice {alice.Health.Value} hp, carol {carol.Health.Value} hp"); ``` It prints: ```text bob was 1v1, carol is 1v2 dropped: 1v1 is gone alice 65 hp, carol 10 hp ``` Bob's answer names `1v1`, and the entity on index 1 is now `1v2`, so `TryGetEntity` fails and Carol keeps her 10 hp: an id kept across the `await` never reaches the wrong entity, and only the system, on the owner thread, writes. ## How to use it fast | Instead of | Do | Why | | ------------------------------------------ | -------------------------------------------------- | ------------------------------- | | `Has()` then `Get()` | `ref var x = ref e.TryGetRef(out bool found)` | One lookup | | `Get()` several times in a method | One `ref` local, used before any structural change | One lookup | | `Get()` to read a tracked component | `Read()` or the generated property | Not stamped as a write | | Looking an id up on every access | Look it up once per method with `TryGetEntity` | The handle then needs no lookup | | A singleton lookup per call from host code | A `SingletonRef` kept from setup | No lookup at all | 1,000 component writes through entity handles, the same after looking each id up with `TryGetEntity`, and 1,000 singleton accesses (`MicroBenchmarks`): | Case | Mean | vs baseline | Allocated | | --------------- | ------- | ----------- | --------- | | HandleAccess | 3.33 μs | 0.26× | 0 B | | TryGetEntity | 3.60 μs | 0.28× | 0 B | | SingletonAccess | 1.01 μs | 0.08× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **A `ref`** is a pointer into a column: no copy, no lookup after the one that produced it. - **Getting it through a handle:** the entity's 16-byte record, then one cache line of the table's lookup. - **Re-validating after an `await`:** `IsAlive` is one record load and a version compare. - **Carrying `[ForEach]` writes across a structural change** costs one copy of the written components, only for the entities whose table changed. ## Pitfalls | Mistake | What happens | Caught by | | ------------------------------------------------------------------- | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Changing a copy (`var hp = e.Get()`) | The table is unchanged | Code review: `ref var` | | A `ref` local across an `await` | Does not compile | The C# compiler | | A `ref` kept after a structural change | Points at a stale copy or another entity's row | Code review: get it again | | A raw index stored instead of the `EntityId` | Names whichever entity reuses the index | Store the `EntityId`; `TryGetEntity` checks the version | | An `Entity` stored in a component | A managed column | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) (warning) | | A `DynamicBuffer` taken by value | Writes go to a shared list, unstamped | [EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012) | | Touching the world after an `await` that resumed on the thread pool | Races with the owner thread | Code review: hand the result over as data. [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) catches only structural changes in a delegate handed to another thread (`Task.Run`, `Parallel.*`), not value writes or code after an `await` | ## Related - [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes): What moves rows, and what a pass sees. - [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components): Handles, `EntityId` and the `Get` / `Read` / `TryGetRef` family. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): Owner threads, and input from other threads. - [Singletons](https://ecs.xgamedev.net/en/docs/guide/singletons): The one kind of storage whose handle you can keep. --- # Change tracking > Visit only the entities whose component was written or removed since a system last ran, with ITrackChanges, [Changed] and [Removed] in C#. URL: https://ecs.xgamedev.net/en/docs/guide/change-tracking Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/change-tracking.md 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]`: it visits only the entities whose `T` was written since its system last ran. `[Removed]` 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. ```csharp public record struct Health(int Value) : IComponent, ITrackChanges; public record struct Replica(int Health) : IComponent; ``` ### Filter the method `[Changed]` selects the rows written after the system's last run. Read the tracked component with `in`. ```csharp 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] 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. ```csharp world.AddSystem(); 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: | Write | Not a write | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ref T` parameters of `[ForEach]` methods (`Span` for batch methods) and of struct jobs (`Writes`) | `in T` parameters, `ReadOnlySpan` | | `Query` items (the enumerator stamps every row it visits) | `TryGet(out T)` (a copy), `Read()` (read-only) | | `entity.Get()`, `TryGetRef(out found)` when found, `GetOrAdd()`, `Set(...)` | `Has()` | | `CreateEntity(...)`, `CreateEntities(...)`, `Instantiate(...)`, `Clone()` with the component | removing the component (a [removal](https://ecs.xgamedev.net/en/docs/guide/change-tracking#removal-detection)) | | `entity.Enable()`, `world.EnableAll()` (the kept value comes back) | `entity.Disable()` (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](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records)). `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](https://ecs.xgamedev.net/en/docs/guide/saves#restart)) | | `entity.Run<…>(ref job)` ([one entity](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-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 true | `entity.Run` that returns false: the job did not run | A [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) 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]` 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(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]` or `[Removed]` reader: the method declares a read of `T`. Outside systems, filter by a tick you read earlier: ```csharp ulong mark = world.ChangeTick; unit.SetHealth(40); // a write after the mark var changed = QueryFilter.Create().Changed(mark); // rows written at or after mark int count = world.Count(changed); foreach (var item in world.Query(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]` 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]` visits the entities that lost a tracked component `T` since the system last ran: ```csharp 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] // set on fire (or the fire written) since the last run static void Lit(ref FireReplica replica) => replica.Burning = true; [ForEach, Removed] // 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. **Once per removal** An entity that lost `T` and still lacks it is visited once, by the system's first run after the removal. Removed again later, it is visited again. **Removed and added back** Removed and added back before the system runs is not a removal (the entity has `T`). `[Changed]` sees it instead, since adding writes the component. **Destroyed entities** Destroyed entities are not reported: they have no row. If clients must learn that an entity left, mark it (a `Despawned` tag the replication reads) and destroy it after the replication has run. **Lacking is not losing** An entity created, instantiated from a [prefab](https://ecs.xgamedev.net/en/docs/guide/prefabs) or cloned without `T` never lost it, so it is not reported. **After a restore** After `world.Restore`, every restored row lacking `T` counts as removed, just as every row having it counts as written: a restore re-sends everything. Outside systems, `QueryFilter.Removed(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): ```csharp // A field of your class: the tick is set per call. private static readonly QueryFilter FireOut = QueryFilter.Create().Removed(0); ulong mark = world.ChangeTick; world.Update(); int extinguished = world.Count(FireOut.Since(mark)); foreach (var item in world.Query(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`. **Components.cs** ```csharp using EasyEcs; // Tracked: every write records its tick, so [Changed] finds the rows written. public record struct Health(int Value) : IComponent, ITrackChanges; // Tracked: a removal records its tick too, so [Removed] finds the units that lost it. public record struct Burning(int Ticks) : IComponent, ITrackChanges; // What the clients were last told about a unit. public record struct Replica(int Health) : IComponent; // How many rows replication sent in the last update. public record struct Sent(int Rows) : ISingletonComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Burning units lose 10 health a tick until the fire goes out. public class BurnSystem : EcsSystem { [ForEach] static void Burn(Entity unit, ref Burning burning, ref Health health) { health.Value -= 10; burning.Ticks--; if (burning.Ticks == 0) { unit.RemoveBurning(); } } } // Sends the health of every unit whose health was written since this system last ran. [UpdateAfter] public class ReplicateHealthSystem : EcsSystem { // OnUpdate runs before the [ForEach] method: each update counts from zero. protected override void OnUpdate() { World.Sent.Rows = 0; } // Health is read with `in`: a `ref` would count as a write. [ForEach, Changed] static void Send(in Health health, ref Replica replica, ref Sent sent) { replica.Health = health.Value; sent.Rows++; } } // Tells the clients that a fire went out: visits each unit that lost Burning since the last run. [UpdateAfter] public class ReplicateFireOutSystem : EcsSystem { [ForEach, Removed] static void FireOut(Entity unit, in Health health) { Console.WriteLine($" {unit}: the fire went out at {health.Value} hp"); } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); world.AddSingleton(); world.AddSystem(); world.AddSystem(); world.AddSystem(); var units = new Entity[1000]; world.CreateEntities(units, new Health(100), new Replica(100)); units[0].SetBurning(2); for (int tick = 1; tick <= 4; tick++) { // A write from outside the systems counts too. if (tick == 3) { units[42].SetHealth(75); } world.Update(); Console.WriteLine($"tick {tick}: sent {world.Sent.Rows} of {units.Length} rows"); } // Outside systems, filter by a tick taken earlier. ulong mark = world.ChangeTick; units[7].SetHealth(1); units[8].SetHealth(1); var writtenSinceMark = QueryFilter.Create().Changed(mark); Console.WriteLine($"written since the mark: {world.Count(writtenSinceMark)}"); ``` It prints: ```text 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]` reader downstream then visits them all. - **Prefer a system to a query.** A `[Changed]` 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()`. - **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]` | Plain `[ForEach]` over every row | | ------------------------------- | -------------- | -------------------------------- | | 10 | 525 ns | 38.6 μs (73× slower) | | 1,000 scattered | 38.9 μs | 67.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](https://ecs.xgamedev.net/en/docs/performance#the-few-rows-that-changed-changedt). ## Pitfalls | Mistake | What happens | Caught by | | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- | -------------------------------------------------------------------- | | Changing a collection inside a component through `in` | The row is not stamped, so `[Changed]` misses it | [EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) | | `[Removed]` on a method that also requires `T` | Asks for rows that have and lack `T` at once: no row passes | [EECS016](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs016) | | `[Removed]` with no component parameter or `[With]` | Nothing names what the method iterates | [EECS003](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs003) | | `ref` parameter that only reads | Every visited row counts as changed | [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) | | `LoadEntitiesInto(..., markWritten: false)` for values the receivers do not have yet | The loaded rows are not changes, so `[Changed]` replication never sends them | Code review: a replicator to new clients sends the full state itself | | Expecting destroyed entities in `[Removed]` | They have no row and are never reported | Mark with a tag, destroy after replicating | | Several `Changed` / `Removed` filters with different ticks | `ArgumentException`: a filter has one tick | At 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()`), 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** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------- | ---------- | --------- | | EasyEcs | Changed | 38.5 μs | 1.00× | 0 B | | EasyEcs | Scan | 61.4 μs | 1.59× | 0 B | | DefaultEcs | WhenChanged | 77.3 μs | 2.01× | 0 B | | Friflo.Engine.ECS | Scan | 53.7 μs | 1.40× | 0 B | | Friflo.Engine.ECS | DirtyTag | 123 μs | 3.2× | 0 B | | Arch | Scan | 109 μs | 2.83× | 0 B | | Arch | DirtyTag | 84.0 μs | 2.18× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The full comparison, with ten written rows and with removals: [Comparison: change tracking](https://ecs.xgamedev.net/en/docs/comparison#change-tracking). ## Related - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): Parameters, filters, ordering and groups of the methods that read changes. - [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries): `QueryFilter`, `Count`, `Any` and struct jobs for ad-hoc readers. - [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers): A list per entity whose every write is tracked. - [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots): Restoring a world counts every row as written, or removed. --- # Dynamic buffers > DynamicBuffer gives each entity its own list (a bag, a path, the hits of a tick) as a change-tracked component that allocates nothing once it has room. URL: https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/dynamic-buffers.md A server keeps many small lists that belong to one entity: the item ids in a bag, the waypoints of a path, the hits a unit took this tick, the orders a player queued. `DynamicBuffer` holds such a list as a component. You add it, query it and take it as a `[ForEach]` parameter like any other component, and every write to the list is a tracked change, so `[Changed>]` finds exactly the bags to send or save. ## When to use it > **Use it for** > > Lists of plain values that only their owner uses and that are sent or saved when they change: item ids or stacks > in a bag, waypoints, recent events, pending orders. Also the links of a [relation](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#relations), > which are buffers of `IRelation` elements. > **Skip it for** > > Items with state of their own that systems query one by one (a sword with durability): make each an entity that > points at its owner. A few values with a fixed maximum (four cooldown slots): a fixed `[InlineArray]` array in an > unmanaged component holds no GC object at all. ## How to use it ### Declare the element The element is a plain struct; it does not implement `IComponent`. `DynamicBuffer` is the component. ```csharp public record struct Loot(int Item); public record struct Sent(int Items) : IComponent; public struct Player : IComponent; ``` ### Create entities with an empty buffer `new DynamicBuffer()` holds no list yet. Each entity gets its own list on its first write, so one value can create a whole wave of entities. ```csharp var players = new Entity[1_000]; world.CreateEntities(players, new DynamicBuffer(), new Sent(), new Player()); foreach (var p in players) p.WriteLoot().EnsureCapacity(8); // room for a full bag: no growth later ``` ### Write through a `ref` The writing methods take the buffer by `ref`, so the write is stamped like any write of a tracked component. ```csharp public class Pickup : EcsSystem { [ForEach, With] static void Collect(ref DynamicBuffer bag) { if (bag.Count == 8) bag.RemoveAt(0); // a full bag drops its oldest item bag.Add(new Loot(1)); } } ``` ### React to the lists that changed A `[Changed>]` method visits only the bags written since its system last ran. It reads them with `in`, which is not a write. ```csharp public class SendBags : EcsSystem { [ForEach, Changed>] static void Send(in DynamicBuffer bag, ref Sent sent) { int items = 0; foreach (var loot in bag) items += loot.Item; sent = new Sent(items); } } ``` ```csharp world.AddSystem(); world.AddSystem(); world.Update(); ``` ### Choosing how to hold a list | The list | Hold it as | | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | Plain values only its owner uses, sent or saved when it changes: item ids or stacks, waypoints, the hits of a tick | **`DynamicBuffer`** | | Items with state of their own (durability, buffs with timers) that systems query or change one by one | **One entity per item** with an [`EntityId` link](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#entityid-keys) to the owner | | A few values with a fixed maximum (4 cooldown slots, the last 8 inputs) | **A fixed `[InlineArray]` array** in an unmanaged component | | Data read and written as a whole with the save (quest progress, settings) | **A collection in a component**, changed through `ref` | A player's bag of loot ids is a buffer; a sword with durability and enchantments is an entity that points at its owner. The full table, with read-mostly and immutable data, is in [ECS principles, rule 8](https://ecs.xgamedev.net/en/docs/ecs-principles#8-choose-how-to-hold-a-collection). ### Reading and writing | Read (`in`, `Read()`, or a `ref`) | Write (a `ref` only: a `ref` parameter, `Get()`, `TryGetRef`) | | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- | | `Count`, `Capacity`, `bag[i]` (read-only), `AsReadOnlySpan()`, `foreach` | `Add`, `AddRange`, `Insert`, `RemoveAt`, `RemoveAtSwapBack`, `Clear`, `EnsureCapacity`, `TrimExcess`, `AsSpan()` (writable) | The writes are extension methods on `ref DynamicBuffer`, so the compiler rejects them on an `in` parameter or on `Read()`: a list cannot change without a tracked write. Outside systems, reach the buffer through its entity. For an element that some code names as `DynamicBuffer`, the generator writes named members: | Generated | Same as | | ------------------ | -------------------------------------------------------------------------- | | `e.Loot` | `e.Read>()`: a `ref readonly`, not stamped | | `e.HasLoot` | `e.Has>()` | | `e.WriteLoot()` | `e.Get>()`: a `ref`, stamped as written | | `e.GetOrAddLoot()` | `e.GetOrAdd>()`: adds an empty buffer first if missing | | `e.RemoveLoot()` | `e.Remove>()` | ```csharp ref var bag = ref player.WriteLoot(); // a ref local: a tracked write bag.Add(new Loot(7)); bag.Insert(0, new Loot(1)); // at the front: the rest shift by one bag.AddRange([new Loot(2), new Loot(3)]); // a span: one copy, one growth at most bag.RemoveAtSwapBack(1); // O(1): the last element fills the hole foreach (ref var loot in bag.AsSpan()) loot = new Loot(loot.Item * 10); // change elements in place bag.TrimExcess(); // give back the room a big bag no longer needs int held = player.Loot.Count; // a read: not stamped ReadOnlySpan items = player.Loot.AsReadOnlySpan(); // the elements, read-only ref var stash = ref hero.GetOrAddLoot(); // an empty buffer if the hero had none ``` A relation's buffer gets no `WriteX()` or `GetOrAddX()`: its links are indexed and change only through [`AddRelation` / `RemoveRelation`](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#relations). ### Copies The list lives in an object the component refers to. A copy of a `DynamicBuffer` value would refer to the same list, so writes through the copy would not be stamped, and storing the copy would give two entities one list. The analyzer rejects every copy ([EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012)): ```csharp public static class Bags { public static int Items(Entity player) { var copy = player.Read>(); // EECS012: a copy of the buffer return copy.Count; } } ``` Use `ref` and `in` parameters, `ref` locals and `Get` / `Read`. A new value is `new DynamicBuffer()` (or `default`), which holds no list. ### Moves, removal, snapshots and prefabs - A row that moves to another table (a component added) keeps its list. - Removing the component or destroying the entity drops the list; adding the component back starts with none. - `world.Capture()` copies the elements and `Restore` copies them back: a world and its [snapshot](https://ecs.xgamedev.net/en/docs/guide/snapshots) never share a list. - `world.Instantiate(prefab)` and `entity.Clone()` give the new entity a list of its own with the same elements. A [prefab](https://ecs.xgamedev.net/en/docs/guide/prefabs) gets its elements with `SetBuffer(...)`: ```csharp var chest = new Prefab().SetBuffer(new Loot(1), new Loot(2)); var opened = world.Instantiate(chest); // its own list: Loot 1, Loot 2 ``` - [`Save`](https://ecs.xgamedev.net/en/docs/guide/saves) writes the elements: unmanaged ones as raw rows, managed ones through Nino. ## Full example A hero picks up a numbered item every tick into a bag that holds four, and a sync system counts the bags that changed. A chest has a bag too, but nothing writes it. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; // An element of a bag: any struct. DynamicBuffer is the component. public record struct Loot(int Item); // A tag: the entities that pick up loot. public struct Collector : IComponent; // The number of the next item to drop. public record struct Drops(int Next) : ISingletonComponent; // How many bags were sent since the start. public record struct Synced(int Bags) : ISingletonComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Every collector picks up the next item. A full bag drops its oldest item first. public class PickupSystem : EcsSystem { const int BagSize = 4; // The bag is taken by `ref`: writing it is a tracked change. [ForEach, With] static void Pick(ref DynamicBuffer bag, ref Drops drops) { if (bag.Count == BagSize) { bag.RemoveAt(0); } drops.Next++; bag.Add(new Loot(drops.Next)); } } // Sends only the bags written since this system last ran. [UpdateAfter] public class SyncBagsSystem : EcsSystem { [ForEach, Changed>] static void Sync(ref Synced synced) { synced.Bags++; } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); world.AddSingleton(); world.AddSingleton(); world.AddSystem(); world.AddSystem(); // An empty buffer holds no list: each entity gets its own on its first write. Entity hero = world.CreateEntity(new DynamicBuffer(), new Collector()); Entity chest = world.CreateEntity(new DynamicBuffer()); // Make room for a full bag now, so the list never grows later. hero.WriteLoot().EnsureCapacity(4); for (int i = 0; i < 6; i++) { world.Update(); } // hero.Loot is a read (Read), not a change. Console.Write("hero's bag:"); foreach (var loot in hero.Loot) { Console.Write($" {loot.Item}"); } Console.WriteLine(); Console.WriteLine($"the chest holds {chest.Loot.Count} items"); Console.WriteLine($"bags synced: {world.Synced.Bags}"); ``` It prints: ```text hero's bag: 3 4 5 6 the chest holds 0 items bags synced: 7 ``` The bag holds the last four items. Seven syncs: the first run sees both bags as new, then only the hero's bag is written, once in each of the five updates that follow. ## How to use it fast | Instead of | Do | Why | | -------------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | Letting a list grow from empty | `EnsureCapacity(n)` once where the size is known | Adding within the capacity allocates nothing | | A new list per tick | `Clear()` and refill | `Clear` keeps the capacity: a list refilled every tick allocates nothing once it reached its size | | `RemoveAt(i)` when the order does not matter | `RemoveAtSwapBack(i)` | O(1) instead of O(count) | | Reading through a `ref` parameter | An `in` parameter | A `ref` stamps the row, and every `[Changed]` reader visits it ([EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025)) | | Keeping a span across `Add` | Take a new span after any call that may grow the list | `Add`, `AddRange`, `Insert`, `EnsureCapacity` and `TrimExcess` may reallocate the array | Measured on 100,000 bags of 8 items, of which 1,000 trade an item per tick and one `[Changed]` system sends the changed bags (`DynamicBufferBenchmark`), against the same bag as a `List` in a tracked component: | Case | List | Mean | vs baseline | Allocated | | ---- | ----- | ------- | ----------- | --------- | | Tick | False | 56.5 μs | — | 0 B | | Tick | True | 61.8 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The buffer and the list it replaces are measured side by side above, and the bag cannot change without the change being tracked. 1,000 actors with a mailbox of four messages unloaded and loaded again each operation (`BufferChurnBenchmark`): the new buffers take the lists of the dead ones. | Case | Mean | vs baseline | Allocated | | ------------- | ------- | ----------- | --------- | | LoadAndUnload | 76.6 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Memory:** one reference per row in the column, plus one object and one array per entity, made by its first write. There is no inline capacity: every list lives on the heap. - **A write** stamps the row once, like any [tracked component](https://ecs.xgamedev.net/en/docs/guide/change-tracking#what-it-costs). - **Adding within the capacity** allocates nothing; growing doubles the array (at least 4 elements). - **A buffer that dies** (its entity destroyed, the component removed) hands its list, emptied, to the next buffer of its element type that the thread creates, so entities that come and go with buffers (actors loaded and unloaded, units spawned and killed) allocate nothing once warm. Only lists that died while none were taken wait there, and a list of more than 4 KB is left to the GC. - **`TrimExcess`** gives back what a list that once grew large no longer needs; an empty list then holds no array. - **Parallel methods** may take a `ref DynamicBuffer`: each chunk writes only its own entities' lists. ## Pitfalls | Mistake | What happens | Caught by | | ---------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------ | | Copying the buffer into a local, a field or another entity | Two owners of one list; writes through the copy are not tracked | [EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012) | | Calling `Add` on an `in` parameter or on `Read()` | Does not compile: the writes need a `ref` | The compiler | | Keeping an `AsSpan()` across an `Add` | The span still points at the old array | Code review: take a new span | | Reading the buffer through a `ref` parameter | Every visited row counts as changed | [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) | | One entity per element of a plain list | An entity, a row and an index entry per item | Use a buffer for plain values | ## Related - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): `[Changed]` and what counts as a write. - [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#relations): `IRelation` buffers: an entity linked to many others. - [Saves](https://ecs.xgamedev.net/en/docs/guide/saves): Buffers are saved with their elements. - [Sample: SaveLoad](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/SaveLoad): Bags that are saved, loaded and moved with their players. --- # Indexes and relations > Find entities by a value (a name, a zone, a score range) or by the entity they point at, with IIndexed and IRelation indexes kept current. URL: https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/indexes-and-relations.md Queries find entities by the components they have. A server also needs them by value: the player named "alice", the units in zone 3, the top ten scores, the items a player owns, the members of a party. Implement `IIndexed` on a component and the world keeps an index of it: every `Set` re-indexes the entity at once, so a lookup never catches up and never scans. Relations are indexes too: a component holding an `EntityId` answers "who points at this entity", and an `IRelation` buffer links one entity to many. ## When to use it > **Use it for** > > Lookups by key (a player by name, units by zone), ordered walks (leaderboards, deadlines, matchmaking brackets), > reverse links (the items of an owner, the arrows of an archer) and many-to-many links (party members, followers). > **Skip it for** > > A key you only filter by in a full pass: a plain `[ForEach]` reads it anyway. Few keys holding many entities each > that you walk whole (16 zones of 100,000 players): [groups](https://ecs.xgamedev.net/en/docs/guide/groups) put each key in its own tables > and walk them at full speed. A dictionary you would keep in sync by hand: the index is that dictionary. ## How to use it ### Value indexes Implement `IIndexed`: `Key` is the value the entity is found by. `world.Index()` creates the index on first use; the generated `world.XIndex` property returns the same one. ```csharp public record struct Callsign(string Value) : IComponent, IIndexed { public string Key => Value; } public record struct Zone(int Id) : IComponent, IIndexed { public int Key => Id; } ``` ```csharp var alpha = world.CreateEntity(new Callsign("alpha"), new Zone(1)); world.CreateEntity(new Callsign("bravo"), new Zone(1)); var zones = world.ZoneIndex; // world.Index(): keep it in a local or a field int inOne = zones.Count(1); // O(1) foreach (var e in zones.Find(1)) { /* every entity in zone 1 */ } if (world.CallsignIndex.TryFind("alpha", out var found)) { /* any entity with that key */ } alpha.SetZone(2); // a Set: the index moves alpha at once int inTwo = zones.Count(2); // 1 ``` Read an indexed component with `in`, `Read()` or the generated property (`alpha.Zone`, a `ref readonly`), and write it with `Set` or the generated `SetX`. A write through a `ref` would change the key behind the index's back, so the analyzer rejects it ([EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015)). A component has one index, with one key type. ### A component as its own key A key can be the whole component: a shop found by its id, an actor found by its address. Make the component `IIndexed` of itself and implement `Key` explicitly: ```csharp public readonly record struct Shop(long Id) : IComponent, IIndexed { Shop IIndexed.Key => this; // explicit: a public Key property would recurse in ToString() } ``` ```csharp var shop = world.CreateEntity(new Shop(7)); if (world.ShopIndex.TryFind(new Shop(7), out var found)) { /* the shop with id 7 */ } ``` On a record struct, a public `Key => this` property joins the generated `ToString()`, which prints `Key`, which prints `Key` again, until the stack overflows. The explicit implementation keeps `Key` out of the record's members. The [Actors sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/Actors) builds on this: one type per kind of actor is its key, its system group and the group's filter. ### Ordered walks and ranges When the key compares (`IComparable`: a score, a level, a deadline), the same index walks in key order: | Call | Visits | | ------------------------------ | ----------------------------------------------- | | `Range(min, max)` | keys from `min` to `max` (inclusive), ascending | | `RangeDescending(min, max)` | the same keys, descending | | `Ascending()` / `Descending()` | every indexed entity in key order | ```csharp public record struct Score(int Points) : IComponent, IIndexed { public int Key => Points; } ``` ```csharp for (int i = 0; i < 100; i++) world.CreateEntity(new Score(i * 10)); int shown = 0; foreach (var leader in world.ScoreIndex.Descending()) // the top of the leaderboard first { if (++shown > 10) break; } foreach (var rival in world.ScoreIndex.Range(400, 500)) { /* a matchmaking bracket */ } ``` The first ordered walk sorts the keys once; from then on the index keeps them sorted as keys appear and disappear. ### `EntityId` keys: one link per entity A component holding an `EntityId` and indexed by it is a link: each arrow has one owner, and the index answers which arrows an owner has. Store the `EntityId`, not the `Entity` handle ([EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017)): the id is 8 bytes, unmanaged and saved with the world, and a handle converts to it implicitly. ```csharp public record struct OwnedBy(EntityId Owner) : IComponent, IIndexed { public EntityId Key => Owner; } public struct Arrow : IComponent; ``` ```csharp var archer = world.CreateEntity(new Health(10)); for (int i = 0; i < 3; i++) world.CreateEntity(new OwnedBy(archer), new Arrow()); int quiver = world.OwnedByIndex.Count(archer); // 3: an array access, no hashing foreach (var arrow in world.OwnedByIndex.Find(archer)) { /* each arrow of the archer */ } ``` An `EntityId` carries the entity's version, so a link to a destroyed entity never matches a later entity that reuses its index. To turn an id back into a handle, `world.TryGetEntity(id, out var entity)` also says whether it still lives. The parent-child link is built in: see [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy). ### Relations: many links per entity An entity holds one component of each type, so an `EntityId` key gives each entity one link. A relation gives it any number: its elements implement `IRelation` and live in a [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers), and `world.Relations()` finds the entities linking to a target. ```csharp public record struct MemberOf(EntityId Target) : IRelation; ``` ```csharp var red = world.CreateEntity(); var blue = world.CreateEntity(); var knight = world.CreateEntity().AddRelation(new MemberOf(red)).AddRelation(new MemberOf(blue)); // in two parties var parties = world.Relations(); // keep it in a local or a field int members = parties.Count(red); // O(1) foreach (var member in parties.Find(red)) { /* each member of red */ } bool inBlue = knight.HasRelation(blue); knight.RemoveRelation(blue); // leaves blue ``` `AddRelation` adds the buffer if the entity has none, then appends the link and indexes it. Read the links with `Read>()` or an `in` parameter; write them with `AddRelation`, `RemoveRelation` or a `Set` of a whole buffer, so the index follows (a `ref` write is [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015)). Once some code names `DynamicBuffer` (a `[ForEach]` parameter, a `Read`), the generator adds named members for the relation: | Generated | Same as | | ----------------------------------------------------- | ------------------------------------------------------------------------------------- | | `e.AddMemberOf(target)` | `e.AddRelation(new MemberOf(target))`, returns the entity | | `e.RemoveMemberOf(target)` | `e.RemoveRelation(target)`, returns how many links went | | `e.LinksMemberOf(target)` | `e.HasRelation(target)` | | `e.MemberOf` / `e.HasMemberOf` / `e.RemoveMemberOf()` | the links (`ref readonly DynamicBuffer`), whether it has any, drop them all | | `world.MemberOfIndex` | `world.Relations()` | ```csharp public record struct PartyCount(int Parties) : IComponent; public class CountParties : EcsSystem { [ForEach] static void Count(in DynamicBuffer parties, ref PartyCount count) => count = new PartyCount(parties.Count); } ``` ```csharp var paladin = world.CreateEntity(new PartyCount()).AddMemberOf(red).AddMemberOf(blue); bool withBlue = paladin.LinksMemberOf(blue); // true paladin.RemoveMemberOf(blue); // 1 link went int linked = paladin.MemberOf.Count; // 1 int inRed = world.MemberOfIndex.Count(red); // the knight and the paladin ``` A relation gets no `WriteX()` or `GetOrAddX()`: its links are indexed, so they change only through the calls above. ### When the target is destroyed What happens to links when their target dies is a rule of your game, and the index can apply it inside every destroy: | `TargetPolicy` | The links to a destroyed entity | Example | | -------------------- | ---------------------------------------------------------------------------------------- | ------------------------------- | | `Keep` (the default) | stay, findable by the dead id (which no later entity has); a system of yours cleans them | an audit trail | | `Remove` | go: the component is removed from its entities, a relation drops the links | an owner loses its pet | | `Destroy` | the linking entities are destroyed too, and what links to them in turn | a summon dies with its summoner | ```csharp world.OwnedByIndex.WhenTargetDestroyed(TargetPolicy.Destroy); // arrows go with their archer world.Relations().WhenTargetDestroyed(TargetPolicy.Remove); // a disbanded party leaves no links archer.Destroy(); int arrowsLeft = world.Count(); // 0 ``` `WhenTargetDestroyed` is set per world and per index. `ChildOf`, the [hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy) link, is `Destroy` from the start. ### Driving a system from an index A `[ForEach]` method can walk an index for each entity it visits: a hazard hurts the units of its zone, a guild totals its members. Take the `World` (or an `Entity`) as a parameter to reach the index; the system then runs alone, which an index needs, since it belongs to the world's owner thread. ```csharp public record struct Hazard(int Zone, int Damage) : IComponent; public class BurnZones : EcsSystem { [ForEach] static void Burn(in Hazard hazard, World world) { foreach (var unit in world.ZoneIndex.Find(hazard.Zone)) { ref var health = ref unit.TryGetRef(out bool found); // one lookup if (found) health.Value -= hazard.Damage; } } } ``` The walk visits only the units of that zone, however many units the world holds. Destroying entities during a `Find` loop is allowed. Changing the indexed component of that index during the loop is not: a key that empties hands its id array to the next key that grows, so the walk could read another key's entities. Collect first, then change. ## Full example Units found by team, by name and by level, arrows that belong to an archer, and heroes in several parties at once. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; // Value indexes: Key is the value an entity is found by. public record struct Team(int Id) : IComponent, IIndexed { public int Key => Id; } public record struct PlayerName(string Value) : IComponent, IIndexed { public string Key => Value; } // An int key compares, so this index can also walk a range of levels in order. public record struct Level(int Value) : IComponent, IIndexed { public int Key => Value; } // A link: each arrow has one owner, and the index lists the arrows of an owner. public record struct OwnedBy(EntityId Owner) : IComponent, IIndexed { public EntityId Key => Owner; } public struct Arrow : IComponent; // A relation: an entity can hold many of these, one per party it is in. public record struct MemberOf(EntityId Target) : IRelation; ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); // ---- Value indexes ---- for (int i = 0; i < 9; i++) { world.CreateEntity(new Team(i % 3), new Level(i + 1)); } world.CreateEntity(new PlayerName("alice"), new Level(42)); // The generated property is world.Index(): keep it in a local or a field. var teams = world.TeamIndex; Console.WriteLine($"team 0: {teams.Count(0)} units"); // Changing Team inside a loop over the team index is not allowed: // collect the units first, then change them. var moving = new List(); foreach (var unit in teams.Find(1)) { moving.Add(unit); } // A Set moves the entity to its new key at once. foreach (var unit in moving) { unit.SetTeam(2); } Console.WriteLine($"team 1: {teams.Count(1)} units, team 2: {teams.Count(2)} units"); // A unique key finds one entity. if (world.PlayerNameIndex.TryFind("alice", out var alice)) { Console.WriteLine($"alice is level {alice.Level.Value}"); } Console.Write("levels 3 to 6:"); foreach (var unit in world.LevelIndex.Range(3, 6)) { Console.Write($" {unit.Level.Value}"); } Console.WriteLine(); // ---- One link per entity: arrows and their owner ---- Entity archer = world.CreateEntity(new Team(0)); for (int i = 0; i < 3; i++) { world.CreateEntity(new OwnedBy(archer), new Arrow()); } var arrows = world.OwnedByIndex; Console.WriteLine($"the archer owns {arrows.Count(archer)} arrows"); // When the archer is destroyed, its arrows are destroyed with it. arrows.WhenTargetDestroyed(TargetPolicy.Destroy); // ---- Many links per entity: parties ---- Entity red = world.CreateEntity(); Entity blue = world.CreateEntity(); Entity hero = world.CreateEntity(); hero.AddRelation(new MemberOf(red)); hero.AddRelation(new MemberOf(blue)); world.CreateEntity().AddRelation(new MemberOf(red)); var parties = world.Relations(); Console.WriteLine($"red has {parties.Count(red)} members, blue has {parties.Count(blue)}"); hero.RemoveRelation(blue); Console.WriteLine($"after the hero left: blue has {parties.Count(blue)}"); archer.Destroy(); Console.WriteLine($"arrows left after the archer died: {world.Count()}"); ``` It prints: ```text team 0: 3 units team 1: 0 units, team 2: 6 units alice is level 42 levels 3 to 6: 3 4 5 6 the archer owns 3 arrows red has 2 members, blue has 1 after the hero left: blue has 0 arrows left after the archer died: 0 ``` The units of team 1 are collected before their team changes, so the walk never reads a key that is being emptied. The arrows go with the archer because of `TargetPolicy.Destroy`; without it they would keep a link to a destroyed entity. ## How to use it fast | Instead of | Do | Why | | ----------------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------- | | `world.Index()` in a hot loop | Keep the index in a local or a field (or use `world.XIndex`) | Creation is cold; the property is O(1) but still a lookup | | `Set` with the key the entity already has | Compare first: `if (unit.Zone.Id != id) unit.SetZone(id);` | A `Set` that keeps the key re-links nothing, but it is still a write | | A scan comparing a key | `Find(key)` / `Count(key)` | O(1), then O(1) per match | | Sorting a query's results each tick | `Range` / `Descending` | The keys stay sorted as they change | | Walking many big keys whole | [`GroupBy`](https://ecs.xgamedev.net/en/docs/guide/groups) | A group's rows are contiguous in their own tables | 100 items changing hands among 100,000, then 100 inventories counted (`IndexBenchmark`); 100 players changing whom they follow, then the followers of 100 players counted and walked (`RelationBenchmark`); 1,000 scores changing, then the top 10 and one bracket read, against a scan keeping the best 10 by hand (`OrderedIndexBenchmark`): | Case | Mean | vs baseline | Allocated | | ------------- | ------- | ----------- | --------- | | TradeAndCount | 5.28 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | -------------- | ------- | ----------- | --------- | | FollowAndCount | 22.7 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ------- | ------- | ----------- | --------- | | Ordered | 75.8 μs | 1.00× | 0 B | | Scan | 307 μs | 4.1× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Nothing until you ask.** The index is built by its first lookup (one walk of the matching tables); a world that never calls `Index` or `Relations` pays nothing. - **Memory:** one node per indexed entity, and one array of ids per key. A relation keeps one 20-byte link per element, recycled, and 8 bytes in its target's list. - **`Count`** is a hash probe, or an array access for an `EntityId` key; **`Find`** adds one step per entity. - **A `Set` that changes the key** unlinks and links the entity (a few array writes; a hash probe for non-entity keys). - **Ordered walks:** the first one sorts the keys; then each new or vanished key costs O(log keys) plus a block move. - **Allocation:** only when the index sees a new key or a larger entity id, never per lookup. - **Target policies:** O(1) per destroyed entity and O(1) per link it had. ## Pitfalls | Mistake | What happens | Caught by | | ---------------------------------------------------------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | | Writing an indexed component through `ref`, `Get()` or a query item | The index keeps the old key | [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015) | | Storing an `Entity` handle in a component | A managed column, write barriers, not saved | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) | | Changing the indexed component inside a `Find` loop over it | The walk can read another key's entities (destroying entities is fine) | Code review: collect first, then change | | A public `Key => this` on a record struct | `ToString()` prints `Key` forever: a stack overflow | Code review: `Shop IIndexed.Key => this;` | | Using an index from another thread | Indexes belong to the owner thread | [Threading](https://ecs.xgamedev.net/en/docs/guide/threading#what-the-world-synchronizes) | | Indexing one component by two key types | `InvalidOperationException`: one index per component | At run time | | A `null` key (the default of a `string`) | The entity is indexed nowhere | By design | ## Compared with other libraries Friflo indexes components (`IIndexedComponent`) and links (`ILinkComponent`, `ILinkRelation`); DefaultEcs has `EntityMultiMap`; Arch keeps relations in a separate package. Each runs its own built-in index here: **100 items change hands among 100,000, then 100 inventories are counted** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | Index | 5.11 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Links | 8.33 μs | 1.63× | 0 B | | DefaultEcs | MultiMap | 7.87 μs | 1.54× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Friend lists: 100 players change whom they follow, then 100 follower lists are read** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------- | ------- | ---------- | --------- | | EasyEcs | Relations | 22.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | LinkRelations | 26.1 μs | 1.19× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Ranges and a zone lookup, with the zone as a value index and as a [group](https://ecs.xgamedev.net/en/docs/guide/groups): **Count a rating range and sum the gold of four zones of 100,000 players** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | ------ | ---------- | --------- | | EasyEcs | Group | 127 μs | 1.00× | 0 B | | EasyEcs | Index | 233 μs | 1.83× | 0 B | | Friflo.Engine.ECS | IndexedComponent | 317 μs | 2.49× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Related - [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy): `ChildOf`, `Children` and destroy cascades. - [Groups](https://ecs.xgamedev.net/en/docs/guide/groups): Tables split by value: the fastest walk of a whole key. - [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers): The buffers that hold relation links. - [Sample: GameLoop](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/GameLoop): A server that finds each player by client id through a value index. --- # Hierarchy > Link entities to a parent with ChildOf, list children with Children, walk a subtree with Descendants, destroy a parent with its subtree. URL: https://ecs.xgamedev.net/en/docs/guide/hierarchy Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/hierarchy.md A ship carries turrets, a turret carries a gun, a squad leader leads its members. `ChildOf(parent)` links an entity to its parent: `world.Children(parent)` lists the children, and destroying the parent destroys its descendants, so a ship that sinks takes its turrets with it without a line of cleanup code. `ChildOf` is an [indexed `EntityId` link](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#entityid-keys) like any other, with the destroy cascade switched on. ## When to use it > **Use it for** > > Entities that live and die with another one: turrets on a ship, items a player carries, members of a squad, the > parts of a vehicle. Moving a player and everything it owns to another world or server. > **Skip it for** > > Links that must not kill the linked entity (a target, a follower): use your own `EntityId` key with `Keep` or `Remove`. > An entity with several "parents" (a member of many parties): use a [relation](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#relations). > Transform propagation is not built in: the [sample below](https://ecs.xgamedev.net/en/docs/guide/hierarchy#transform-propagation) is a system you write. ## How to use it ### Attach children Give the child a `ChildOf` with the parent's id (a handle converts to it). ```csharp public record struct Name(string Value) : IComponent; ``` ```csharp var ship = world.CreateEntity(new Name("ship")); var turret = world.CreateEntity(new Name("turret"), new ChildOf(ship)); var gun = world.CreateEntity(new Name("gun"), new ChildOf(turret)); ``` ### List them `world.Children(parent)` returns the entities whose `ChildOf` points at the parent: O(1), then O(1) per child. The first call indexes every `ChildOf` once. ```csharp foreach (var child in world.Children(ship)) { /* the turret */ } ``` ### Walk a subtree: Descendants `world.Descendants(root)` walks the whole subtree below the root, depth first, each entity before its own children; the root itself is not one of them. It costs O(1) per entity and allocates nothing once warm. Use it where a whole tree is the unit (saving, moving or counting it); propagation that needs each parent's result goes through [`Children` level by level](https://ecs.xgamedev.net/en/docs/guide/hierarchy#transform-propagation). ```csharp int parts = 0; foreach (var part in world.Descendants(ship)) parts++; // the turret, then its gun ``` - **Destroying during the walk** is allowed: an entity destroyed before the walk reaches it is skipped. - **A walk inside a walk** works: the inner one allocates a stack of its own (the outer one holds the world's). - **A `ChildOf` cycle** (an entity that is its own ancestor) throws `InvalidOperationException` when the walk reaches it. - **Changing `ChildOf` during the walk** (re-parenting, detaching) is not allowed: it rewrites the child lists the walk is reading. Collect first, then change. ### Re-parent and detach `ChildOf` is a value like any other: set a new one to re-parent, remove it to make the entity a root. ```csharp gun.Set(new ChildOf(ship)); // the gun now hangs on the ship turret.Remove(); // the turret is a root ``` ### Destroy a parent Destroying a parent destroys its children, and theirs, in the same call. ```csharp ship.Destroy(); // the gun goes with it; the detached turret stays bool gunAlive = gun.IsAlive; // false ``` ### Changing what a destroy does `ChildOf` starts with `TargetPolicy.Destroy`. Like any [target policy](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#target-policies) it can be changed per world: `Remove` makes the children of a destroyed parent roots, `Keep` leaves their `ChildOf` pointing at the dead id. ```csharp world.Index().WhenTargetDestroyed(TargetPolicy.Remove); // orphans become roots ``` - A child that holds a [cleanup component](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable#cleanup-components) is retired, not freed: it keeps its cleanup components with the `Destroyed` tag, and its own children go with it. - A cycle (an entity that is its own ancestor) ends: destroying any of them destroys the loop. - `ChildOf` cannot be disabled (`Disable()` throws): a parent's destroy must find its children. ### Transform propagation EasyEcs has no transform component. Propagation is a system: start at the roots (`Without`) and walk down with `Children`, so each world position is computed from its parent's new one. ```csharp public record struct LocalPosition(float X, float Y) : IComponent; public record struct WorldPosition(float X, float Y) : IComponent; ``` ```csharp public class PropagateTransforms : EcsSystem { // Roots: their world position is their local one; then each subtree follows its parent. [ForEach, Without] static void FromRoot(Entity root, in LocalPosition local, ref WorldPosition position) { position = new WorldPosition(local.X, local.Y); Follow(root, position); } static void Follow(Entity parent, WorldPosition at) { foreach (var child in parent.World.Children(parent)) { ref readonly var local = ref child.LocalPosition; var position = new WorldPosition(at.X + local.X, at.Y + local.Y); child.WorldPosition = position; Follow(child, position); } } } ``` ```csharp world.AddSystem(); var hull = world.CreateEntity(new LocalPosition(10, 0), new WorldPosition()); var mount = world.CreateEntity(new LocalPosition(0, 2), new WorldPosition(), new ChildOf(hull)); var barrel = world.CreateEntity(new LocalPosition(1, 0), new WorldPosition(), new ChildOf(mount)); world.Update(); // barrel: WorldPosition(11, 2) ``` The method takes an `Entity`, so the system runs alone (it reads and writes other entities' components). Children are in other tables than the roots (they have `ChildOf`), so writing them never moves the row the pass stands on. Nothing here allocates. ### Moving a hierarchy `MoveEntities` and `SaveEntities` take the entities you list, not their children. Collect a hierarchy with `Descendants` and move it together: a child whose parent stays behind arrives without its `ChildOf` (a root there), and `MoveEntities` destroys the originals with their children, so a child you did not list is lost. `MoveEntities` takes a `ReadOnlySpan`: pass the list's span (`CollectionsMarshal.AsSpan`) rather than a copy of it. See [migration](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#move-entities). ```csharp using System.Runtime.InteropServices; var player = world.CreateEntity(new Name("bob")); world.CreateEntity(new Name("sword"), new ChildOf(player)); var group = new List { player.Id }; foreach (var part in world.Descendants(player)) group.Add(part.Id); // children, grandchildren, ... using var other = new World(); world.MoveEntities(other, CollectionsMarshal.AsSpan(group)); // bob and his sword, still linked ``` ## Full example A ship with a turret and a gun: world positions follow the parents, the ship's subtree is listed, then the gun is re-parented, the turret detached, and the ship destroyed with what still hangs on it. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Name(string Value) : IComponent; // The position relative to the parent (or to the world, for a root). public record struct LocalPosition(float X, float Y) : IComponent; // The position in the world, computed by PropagateTransforms. public record struct WorldPosition(float X, float Y) : IComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Computes every world position from the roots down, // so each child follows its parent's new position. public class PropagateTransforms : EcsSystem { // Roots have no ChildOf: their world position is their local one. [ForEach, Without] static void FromRoot(Entity root, in LocalPosition local, ref WorldPosition position) { position = new WorldPosition(local.X, local.Y); Follow(root, position); } static void Follow(Entity parent, WorldPosition parentPosition) { foreach (var child in parent.World.Children(parent)) { LocalPosition local = child.LocalPosition; float x = parentPosition.X + local.X; float y = parentPosition.Y + local.Y; var position = new WorldPosition(x, y); child.WorldPosition = position; Follow(child, position); } } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); world.AddSystem(); // A child points at its parent with ChildOf. Entity ship = world.CreateEntity(new Name("ship"), new LocalPosition(10, 0), new WorldPosition()); Entity turret = world.CreateEntity( new Name("turret"), new LocalPosition(0, 2), new WorldPosition(), new ChildOf(ship)); Entity gun = world.CreateEntity( new Name("gun"), new LocalPosition(1, 0), new WorldPosition(), new ChildOf(turret)); world.Update(); Console.WriteLine($"gun at {gun.WorldPosition}"); foreach (var child in world.Children(ship)) { Console.WriteLine($"ship > {child.Name.Value}"); } // Descendants walks the whole subtree, depth first: each entity before its own children. Console.Write("ship's subtree:"); foreach (var part in world.Descendants(ship)) { Console.Write($" {part.Name.Value}"); } Console.WriteLine(); // Re-parent: set a new ChildOf. Detach: remove it, and the entity is a root. gun.Set(new ChildOf(ship)); turret.Remove(); // ChildOf is an indexed component: its index counts the children of a parent. var children = world.Index(); Console.WriteLine($"ship: {children.Count(ship)} child, turret: {children.Count(turret)} children"); // Destroying a parent destroys its children: the gun goes with the ship. ship.Destroy(); Console.WriteLine($"turret alive: {turret.IsAlive}, gun alive: {gun.IsAlive}"); Console.WriteLine($"{world.EntityCount} entity left"); ``` It prints: ```text gun at WorldPosition { X = 11, Y = 2 } ship > turret ship's subtree: turret gun ship: 1 child, turret: 0 children turret alive: True, gun alive: False 1 entity left ``` The gun's world position adds its parents' offsets: 10 + 0 + 1 and 0 + 2 + 0. `Children` lists only the turret; `Descendants` reaches the gun below it. After the turret is detached it survives the ship; the gun, re-parented to the ship, does not. ## How to use it fast - **Destroy the root.** One `Destroy` follows the whole subtree inside the structural gate, with no recursion (a stack of targets). Destroying children one by one before their parent does the same work in more calls. - **Keep depth shallow when you propagate.** The walk above costs one `Children` lookup per entity; flat hierarchies (a ship and its turrets) walk fastest. - **`DestroyEntities()`** destroys a whole table at once and still applies the cascade. 1,000 squads (a leader and 10 members) created, then the leaders destroyed: with members as `ChildOf` their leader (`Cascade`), and with a link of your own under `TargetPolicy.Remove` (`RemoveLinks`, `HierarchyBenchmark`): | Case | Mean | vs baseline | Allocated | | ----------- | ------ | ----------- | --------- | | Cascade | 590 μs | 1.00× | 0 B | | RemoveLinks | 516 μs | 0.88× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Nothing until the first `ChildOf`.** A world without a table holding `ChildOf` does not look for children when it destroys an entity. - **Memory:** the `ChildOf` column (8 bytes per row) and the index of an `EntityId` key (one node per child). - **`Children`:** O(1), then O(1) per child; the first call indexes every `ChildOf`. - **`Descendants`:** O(1) per entity of the subtree, on a stack the world keeps (0 B once warm). - **A cascade:** O(1) per destroyed entity, plus O(1) per child it had. ## Pitfalls | Mistake | What happens | Caught by | | ----------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | | Writing `ChildOf` through a `ref` | The index keeps the old parent | [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015) | | A parent pointer of your own as an `Entity` field | A managed column, not saved, no cascade | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) | | Moving a parent without its children | The children stay and die with the destroyed original | Collect the group with `Descendants` | | Collecting a tree with `Children` alone | Grandchildren are left out | `Descendants` walks every level | | A `ChildOf` cycle walked with `Descendants` | `InvalidOperationException` when the walk reaches it | At run time | | Re-parenting or detaching inside a `Descendants` loop | The walk reads child lists that are being rewritten | Code review: collect first, then change | | `Disable()` | `InvalidOperationException` | At run time | | Expecting world positions without a system | There is no built-in transform | Write the [propagation system](https://ecs.xgamedev.net/en/docs/guide/hierarchy#transform-propagation) | ## Compared with other libraries Friflo has a built-in hierarchy (`AddChild`), but deleting a parent detaches its children, so they are deleted first; Arch and DefaultEcs have none. The same squads, created and destroyed with their members: **1,000 squads of 11: create, then destroy the leaders with their members** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | ChildOf | 452 μs | 1.00× | 0 B | | Friflo.Engine.ECS | AddChild | 1.06 ms | 2.35× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Related - [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations): `EntityId` keys, relations and target policies. - [Cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable): Entities that release a resource before they go. - [Migration and unload](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload): Moving a player and what it owns to another world. - [Sample: SaveLoad](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/SaveLoad): A player and the swords that are its children, saved, loaded and moved to another world. --- # Groups > EasyEcs GroupBy splits a world's tables by an IGroup value, so a query of one zone, map or match walks only its own contiguous rows. URL: https://ecs.xgamedev.net/en/docs/guide/groups Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/groups.md A world often holds many zones, maps or matches, and most work touches one of them: move the units of zone 3, send match 12 its state. `GroupBy()` splits the world's tables by the value of an `IGroup` component, so entities of one group share tables of their own. `QueryFilter.InGroup(group)` then walks only that group's rows, contiguous in memory, at the speed of a plain query over a smaller world. > **Not system groups** > > These are groups of entities. Groups of *systems* that run at their own cadence (`ISystemGroup`, > `[UpdateInGroup]`, `World.Update()`) are another feature: see [Systems](https://ecs.xgamedev.net/en/docs/guide/systems). ## When to use it > **Use it for** > > A few to a few hundred partitions, each holding many entities and walked whole: zones or maps of one server, matches > or rooms, teams in a big battle. Entities that change partition now and then (a player walking to the next zone). > **Skip it for** > > Keys with few entities each (a guild id, an owner): each group costs tables of its own, so use a > [value index](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#value-indexes). Values that change every tick: each change moves > the row. A world per partition when the partitions never interact: [one world per thread](https://ecs.xgamedev.net/en/docs/guide/threading#recommended-one-world-per-thread) > needs no filter at all. ## How to use it ### Mark the component `IGroup.Group` is the partition the entity belongs to. ```csharp public record struct Zone(int Id) : IComponent, IGroup { public int Group => Id; } ``` ### Group the world at setup `GroupBy()` moves the existing entities to their groups' tables and keeps every later write in place: entities created with a `Zone` go straight to their group's table. ```csharp world.GroupBy(); // once, before the world fills for (int i = 0; i < 9; i++) world.CreateEntity(new Zone(i % 3), new Health(10 * i)); ``` ### Walk one group `InGroup(group)`, generated as `InZone(group)` for `Zone`, requires `T` with that group: only the group's tables are walked. Keep filters in `static readonly` fields; a filter holds one group. ```csharp public struct SumHealth : IForEach { public int Total; public static int Writes => 0; // reads only: no row counts as written public void Execute(ref Health health) => Total += health.Value; } public static class Zones { public static readonly QueryFilter One = QueryFilter.Create().InZone(1); } ``` ```csharp int inOne = world.Count(Zones.One); // 3 var sum = new SumHealth(); world.ForEach(ref sum, Zones.One); // a struct job over zone 1 only foreach (var item in world.Query(Zones.One)) { /* the same rows, as a query */ } ``` ### Move an entity to another group Write the new value with `Set` (or the generated `SetX`): the entity moves to its group's table at once, one row copy. ```csharp var walker = world.CreateEntity(new Zone(1), new Health(50)); walker.SetZone(2); // now walked by InGroup(2) ``` A grouped component is written only with `Set`: a write through a `ref` would change the value without moving the row, so the analyzer rejects it as it does for indexed components ([EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015)). `Set` is allowed while a query walks the group. ### Groups in systems `[ForEach]` filters are attributes and cannot name a group value. A system that works on one group at a time runs a struct job from `OnUpdate`, with the group it reads from a singleton: ```csharp public record struct ActiveZone(int Id) : ISingletonComponent; public struct Regenerate : IForEach { public void Execute(ref Health health) => health.Value += 1; } public class RegenerateActiveZone : EcsSystem { protected override void OnUpdate() { var filter = QueryFilter.Create().InZone(World.ActiveZone.Id); var job = new Regenerate(); World.ForEach(ref job, filter); } } ``` An `OnUpdate` override runs alone in its stage. Building the filter per update is cheap: a `QueryFilter` holds no object reference. ### What follows a grouping | Operation | Lands in | | ---------------------------------------------------------------- | ---------------------------------------------------------------------- | | `CreateEntity`, `CreateEntities` | the group of the value, directly (no move) | | `Set`, `SetAll` of the grouped component | the new value's group (one row copy if it changed) | | `Instantiate(prefab)`, `Clone()`, `LoadEntities`, `MoveEntities` | the group of the copied value | | `Restore(snapshot)` | the groups the snapshot had | | `Load(bytes)` | the groups of this world's `GroupBy` calls (a save holds no groupings) | In a world that never called `GroupBy()`, every table holds group 0: `InGroup(0)` matches every entity with `T`. ## Full example Nine units in three zones. A system heals only the units of the active zone, a struct job sums the health of one zone, and three units walk from zone 2 into zone 1. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; // IGroup: the world keeps the entities of each zone in tables of their own. public record struct Zone(int Id) : IComponent, IGroup { public int Group => Id; } public record struct Health(int Value) : IComponent; // The zone players are in: the only one that is simulated. public record struct ActiveZone(int Id) : ISingletonComponent; ``` **Jobs.cs** ```csharp using EasyEcs; // Struct jobs: a pass over the rows a filter selects, with no delegate. public struct Regenerate : IForEach { public void Execute(ref Health health) { health.Value += 1; } } public struct SumHealth : IForEach { public int Total; // The job only reads: no component counts as written (the default, -1, is all of them). public static int Writes => 0; public void Execute(ref Health health) { Total += health.Value; } } ``` **Systems.cs** ```csharp using EasyEcs; // Heals the units of the active zone only. [ForEach] attributes cannot name a group value, // so the system runs a struct job with an InGroup filter from OnUpdate. public class RegenerateActiveZone : EcsSystem { protected override void OnUpdate() { int zone = World.ActiveZone.Id; var inZone = QueryFilter.Create().InZone(zone); var job = new Regenerate(); World.ForEach(ref job, inZone); } } ``` **Zones.cs** ```csharp using EasyEcs; public static class Zones { // Filters are values: build them once and keep them in fields. A filter holds one group. public static readonly QueryFilter One = QueryFilter.Create().InZone(1); public static readonly QueryFilter Two = QueryFilter.Create().InZone(2); // The units and total health of one zone. Walks the tables of that zone only. public static string Describe(World world, QueryFilter zone) { var sum = new SumHealth(); world.ForEach(ref sum, zone); return $"{world.Count(zone)} units, {sum.Total} hp"; } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); // Group the world before it fills: every entity then lands in its zone's tables directly. world.GroupBy(); world.SetActiveZone(Id: 1); world.AddSystem(); for (int i = 0; i < 9; i++) { world.CreateEntity(new Zone(i % 3), new Health(10 * i)); } world.Update(); Console.WriteLine($"zone 1: {Zones.Describe(world, Zones.One)}"); // A new value moves the entity to the tables of its new zone. Set is allowed while a query walks. foreach (var item in world.Query(Zones.Two)) { item.Entity.SetZone(1); } Console.WriteLine($"zone 1: {Zones.Describe(world, Zones.One)}"); Console.WriteLine($"zone 2: {Zones.Describe(world, Zones.Two)}"); ``` It prints: ```text zone 1: 3 units, 123 hp zone 1: 6 units, 273 hp zone 2: 0 units, 0 hp ``` Only the three units of zone 1 were healed (120 + 3). The three from zone 2 arrive with their 150 health; zone 2 is empty after they leave. ## How to use it fast - **Group at setup.** `GroupBy()` on a full world moves every entity once; on an empty one it costs nothing. - **Hoist the filters.** One `static readonly` filter per hot group, or a filter per update as above. - **Group by what you walk, index by what you look up.** A group wins when you walk all of a big group; an index wins when a key holds a handful of entities. 100,000 players in 16 zones; 100 players change zones, then the health of the players of 4 zones is summed: as a group, as a value index and as a plain component a scan compares (`GroupBenchmark`): | Case | Mean | vs baseline | Allocated | | ----- | ------- | ----------- | --------- | | Group | 47.4 μs | 1.01× | 0 B | | Index | 138 μs | 2.93× | 0 B | | Scan | 742 μs | 16× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Memory:** a table per group for each combination of components, with its columns' spare capacity. Thousands of tiny groups fragment the world: that is a job for an index. - **Changing group:** one row copy (like adding a component the table has no column for). - **Walking a group:** the group's own rows only; no per-row test of the value. - **Without `GroupBy`:** a `Set` of an `IGroup` component in a world that never grouped by it costs one null check more; components that are not `IGroup` skip even that (the test is a constant the JIT folds away). The component is still written only with `Set`, grouped or not. ## Pitfalls | Mistake | What happens | Caught by | | --------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | | Writing the grouped component through a `ref` | The row stays in its old group | [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015) | | A group per player, guild or owner | A table per key: memory and fragmentation | Use a [value index](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#value-indexes) | | A value that changes every tick | A row copy per change | Keep it a plain component | | Two `InGroup` calls in one filter | A filter holds one group: the last one counts, and both components are still required | Code review | | `GroupBy` during a pass | Throws: it moves rows | Call it at setup | ## Compared with other libraries Friflo, Arch and DefaultEcs have no grouping by value. The closest is a value index; here are both, against Friflo's indexed component, counting a rating range and summing the gold of four zones: **Count a rating range and sum the gold of four zones of 100,000 players** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | ------ | ---------- | --------- | | EasyEcs | Group | 127 μs | 1.00× | 0 B | | EasyEcs | Index | 233 μs | 1.83× | 0 B | | Friflo.Engine.ECS | IndexedComponent | 317 μs | 2.49× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Related - [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations): Lookups by key, ranges and links. - [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries): `QueryFilter`, `Count`, `Query` and struct jobs. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): One world per thread: partitions that never meet. - [Sample: GameLoop](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/GameLoop): System groups, the other kind of group: input, the tick and replication, each at its own cadence. --- # Snapshots > Copy a whole world into memory with Capture and put it back with Restore, for rollback netcode, replays and test resets, allocation-free when reused. URL: https://ecs.xgamedev.net/en/docs/guide/snapshots Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/snapshots.md `world.Capture()` copies the world's entities, their components and its singletons into a `WorldSnapshot`, and `world.Restore(snapshot)` puts them back, any number of times. A turn-based server undoes a move, a rollback server rewinds a few ticks to apply a late input and re-simulates, a replay jumps back, a test resets its world. Capturing into a snapshot you keep reuses its arrays, so capturing every tick allocates nothing. ## When to use it > **Use it for** > > Undoing a turn, rollback and client-side prediction (a ring of recent ticks), replays within a session, resetting a > world between tests or matches. > **Skip it for** > > Persistence: a snapshot lives in memory and shares managed references with the world. Use [saves](https://ecs.xgamedev.net/en/docs/guide/saves) > for disk and other processes. Capturing millions of entities every tick: each capture copies every row. ## How to use it ### Capture and restore ```csharp var before = world.Capture(); // O(entities × components) int held = before.EntityCount; // the alive entities it holds: log it, or size a ring by it world.Update(); // simulate a turn bool turnAccepted = hero.Health.Value > 0; // the game's rule: a turn that kills the hero is undone if (!turnAccepted) world.Restore(before); // same entities, same values, same singletons ``` A snapshot stays as it was after a restore, so it can be restored again: ```csharp world.Update(); world.Restore(before); // back to the same state a second time ``` ### Reuse snapshots for rollback `Capture(into)` overwrites a snapshot of this world and reuses its arrays. A ring of the last ticks then costs no allocation once its snapshots are large enough. ```csharp public static class Rollback { public const int Ticks = 8; } ``` ```csharp var history = new WorldSnapshot[Rollback.Ticks]; for (int tick = 0; tick < 100; tick++) { history[tick % Rollback.Ticks] = world.Capture(history[tick % Rollback.Ticks]); // null the first time: a new one world.Update(); } world.Restore(history[(100 - 3) % Rollback.Ticks]); // back three ticks, then re-simulate ``` ### What a snapshot holds - **Entities and components, copied by value.** A managed reference inside a component (a `string`, an array, a `List`) is shared with the world, not cloned: a collection in a component comes back as it is now, not as it was. A [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) is the exception: its elements are copied on capture and on restore. Disabled components keep their kept values. - **Singletons, copied by value.** After `Restore` every singleton has the snapshot's value in its existing storage, so a `SingletonRef` taken before keeps working; singletons added after the capture are removed. - **Handles.** Handles to entities alive in the snapshot are valid again. Every other handle is stale, including handles to entities created after the capture, even when a later entity reuses their id. - **Not systems, options or the `GroupBy` configuration.** Systems keep running as registered, and the world keeps its `GroupBy` calls; tables created after the capture stay, empty. What a snapshot does hold is each row's [group](https://ecs.xgamedev.net/en/docs/guide/groups): every entity comes back in the group table it was in at the capture. ### What a restore tells the rest of the world - **Change tracking:** every restored row of a tracked component counts as written, and every restored row lacking one counts as removed, so [replication](https://ecs.xgamedev.net/en/docs/guide/change-tracking#removal-detection) re-sends the restored state. - **Indexes** re-index from scratch on their next lookup. - **Relations** re-index too. Both calls take the structural gate and throw while a query iterates: call them between updates, or from a system's `OnUpdate` outside its `[ForEach]` methods. A snapshot belongs to the world it was taken from (`ArgumentException` otherwise), and one taken before [`RemoveTypes`](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#remove-types) cannot be restored after it (`InvalidOperationException`). ## Full example A turn of poison undone: the world is captured before the turn, five updates and a new entity happen, and the restore brings back the hero's health and the entity count. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Health(int Value) : IComponent; // A tag: poisoned units lose health every tick. public struct Poisoned : IComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Poisoned units lose 10 health a tick. public class PoisonSystem : EcsSystem { [ForEach, With] static void Hurt(ref Health health) { health.Value -= 10; } } ``` **Program.cs** ```csharp using EasyEcs; using var world = new World(); world.AddSystem(); Entity hero = world.CreateEntity(new Health(100), new Poisoned()); // Before the turn: a copy of every entity, component and singleton. WorldSnapshot beforeTurn = world.Capture(); for (int i = 0; i < 5; i++) { world.Update(); } Entity minion = world.CreateEntity(new Health(5)); Console.WriteLine($"after the turn: hero {hero.Health.Value} hp, entities: {world.EntityCount}"); // Undo the turn. Handles from before the capture are valid again; the minion's is stale. world.Restore(beforeTurn); Console.WriteLine($"restored: hero {hero.Health.Value} hp, entities: {world.EntityCount}"); Console.WriteLine($"minion alive: {minion.IsAlive}"); ``` It prints: ```text after the turn: hero 50 hp, entities: 2 restored: hero 100 hp, entities: 1 minion alive: False ``` The minion was created after the capture, so the restore removes it and its handle stays stale even if a later entity reuses its id. ## How to use it fast | Instead of | Do | Why | | --------------------------------------- | -------------------------------------------- | ------------------------------------------------------ | | `Capture()` every tick | `Capture(snapshot)` into a kept snapshot | Reuses its arrays: nothing allocated once large enough | | A snapshot every tick of a huge world | Every few ticks, or a smaller world per zone | Capture is O(entities × components) | | A snapshot for disk | `Save` / `Load` | Bytes, field hashes, other processes | | Collections in components you roll back | `DynamicBuffer` | Buffers are copied; other collections are shared | 100,000 entities in two tables with a singleton: a capture into a new snapshot, a restore, and for comparison a save into a reused buffer and a load (`SnapshotBenchmark`): | Case | Mean | vs baseline | Allocated | | ------- | ------- | ----------- | --------- | | Capture | 931 μs | — | 2.67 MB | | Restore | 428 μs | — | 0 B | | Save | 262 μs | — | 0 B | | Load | 1.00 ms | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The capture's allocation is the new snapshot itself; `Capture(into)` reuses one. ## What it costs - **Memory:** a copy of every row, every singleton and the entity records. - **Time:** O(entities × components + tables + singletons) both ways; rows are copied column by column. - **After a restore:** one re-indexing walk per index on its next lookup, and every tracked row counts as changed. - **Worlds that never capture** pay nothing. ## Pitfalls | Mistake | What happens | Caught by | | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------ | | Expecting a `List` in a component to roll back | It is shared: it comes back as it is now | Use `DynamicBuffer` | | Capturing or restoring while a query iterates | `InvalidOperationException` | At run time | | Restoring a snapshot into another world | `ArgumentException` | At run time | | Restoring a snapshot taken before [`RemoveTypes`](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#remove-types) | `InvalidOperationException`: its tables are gone | At run time: capture again after `RemoveTypes` | | Keeping handles of entities created after the capture | They are stale after the restore | `IsAlive` | | Writing snapshots to disk | They are object graphs, not bytes | Use [saves](https://ecs.xgamedev.net/en/docs/guide/saves) | | Capturing or restoring from another thread | Structural changes belong to the owner thread | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) | ## Related - [Saves](https://ecs.xgamedev.net/en/docs/guide/saves): The world as bytes, for disk and other processes. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): A restore counts every row as written or removed. - [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers): Lists whose elements a snapshot copies. --- # Save and load > Write a whole C# ECS world to bytes with World.Save and read it back with World.Load in any process: same ids, raw unmanaged rows, Nino for managed data. URL: https://ecs.xgamedev.net/en/docs/guide/saves Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/saves.md A server restarts and must come back with its world: players where they stood, timers where they were, links between entities intact. `world.Save(output)` writes the entities (ids and versions), their components and the singletons as bytes, and `world.Load(bytes)` puts them into a world of this process or another one. Unmanaged components are their raw rows, one block per column; managed ones, and the components marked `[NinoType]`, go through [Nino](https://github.com/JasonXuDeveloper/Nino). Saving and loading again into the same buffers allocates nothing. ## When to use it > **Use it for** > > Persistence across restarts, replays on disk, crash dumps, shipping a world to another process (a test harness, a > replay viewer), keeping data through a [hot reload](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#hot-reload). > **Skip it for** > > Rolling back inside one process: a [snapshot](https://ecs.xgamedev.net/en/docs/guide/snapshots) is faster and needs no encoding. Moving a > player to another server: [`SaveEntities`](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#save-entities) writes just the group. > Saving only what persists of an entity and loading it onto a live one: [a record](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records) > is `SaveEntities` with a `ComponentSet`, loaded by `LoadEntitiesInto`. ## How to use it ### Declare the components Unmanaged components need nothing. A managed component (one with a `string`, an array, a class) needs a Nino formatter: mark it `[NinoType]` and make it `partial`. The EasyEcs package brings Nino with its generator, so the project references nothing else. Mark an unmanaged component `[NinoType]` too when its shape will change between builds ([below](https://ecs.xgamedev.net/en/docs/guide/saves#versioning)). ```xml ``` ```csharp using Nino.Core; public record struct Stock(int Gold, int Wood) : IComponent; // unmanaged: saved as raw rows public record struct Clock(long Tick) : ISingletonComponent; [NinoType] public partial record struct PlayerName(string Value) : IComponent; // managed: Nino writes it ``` ### Save `Save` writes into any `IBufferWriter`. A `NinoArrayBufferWriter` is written directly; another writer gets a copy from the world's own buffer. ```csharp world.CreateEntity(new PlayerName("alice"), new Stock(10, 3)); world.SetClock(1234); var output = new NinoArrayBufferWriter(); world.Save(output); // entities, components, singletons File.WriteAllBytes("world.sav", output.WrittenSpan.ToArray()); ``` ### Load `Load` replaces the world's entities, components and singletons with the save's. Entities keep their ids and versions, so `EntityId`s stored in components still point at the same entities, and handles made before the save work again. ```csharp using var restarted = new World(); restarted.Load(File.ReadAllBytes("world.sav")); // same ids, values and clock long tick = restarted.Clock.Tick; // 1234 ``` ### What a save holds | Saved | Not saved | | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | Every alive entity, with its id and version | Systems, `WorldOptions` | | Every component, unmanaged as raw rows, managed through Nino | Indexes (they rebuild on the next lookup) | | Disabled components, with their kept values | Groupings (`Load` follows this world's `GroupBy` calls) | | [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) elements | Change ticks (every loaded row counts as written, or none with `markWritten: false`: [restart](https://ecs.xgamedev.net/en/docs/guide/saves#restart)) | | Every singleton | | Types are recorded by their Nino type id (a hash of the namespace-qualified name), and each column is a length-prefixed slice, so a load skips the components this process has no type for. A type is found when the process used it, or when the generator registered it: every component and singleton of a compilation that uses EasyEcs is registered when its module loads. ### Restart without counting the load as changes A restart resumes the world of the previous process: it saves between two ticks, the new process loads the save, adds its systems and goes on. By default every loaded row counts as written, so a `[Changed]` system that writes records or replicates would send the whole world again on its first run. `Load(bytes, markWritten: false)` loads the rows without a change tick: no row counts as written or removed, also for the systems added after the load, and what code writes from then on is seen as usual. ```csharp public record struct Balance(int Gold) : IComponent, ITrackChanges; // tracked: written records are saved public record struct Outbox(int Records) : ISingletonComponent; public class SaveBalances : EcsSystem { [ForEach, Changed] private static void Save(ref Outbox outbox) => outbox.Records++; // one record per changed balance } ``` ```csharp var bank = new World(); // the old process bank.SetOutbox(0); bank.CreateEntity(new Balance(100)); var previous = new NinoArrayBufferWriter(); bank.Save(previous); // between two ticks using var resumed = new World(); // the new process resumed.Load(previous.WrittenSpan, markWritten: false); // the records hold these values resumed.AddSystem(); resumed.Update(); int records = resumed.Outbox.Records; // 0: no loaded balance is a change ``` The singletons come from the save (`Outbox` here), so the new process adds only those the save did not hold, as at [startup](https://ecs.xgamedev.net/en/docs/guide/hosting#persistence). A system added later to a world that already holds its state, whatever wrote it, can start from the current tick instead: `world.AddSystem(changesFromNow: true)` makes its first run visit only what is written after the call ([ticks](https://ecs.xgamedev.net/en/docs/guide/change-tracking#ticks)). ### When the code changed How a component may change depends on how it is written. A plain unmanaged component is its raw rows: the save records its size and a hash of its fields (names, types, layout attributes), and only the same shape loads them. A `[NinoType]` component, managed or unmanaged, is written by its Nino formatter, and its [format](https://nino.xgamedev.net/en/docs/v4/evolving-data) decides what may change: `Positional` (the default) reads only the shape it wrote, `VersionTolerant` reads rows written before members were appended, `Keyed` also takes members inserted, removed or reordered. A load refuses what it cannot read, with an `InvalidDataException`, and leaves the world as it was: | Change since the save | Load | | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- | | A component type added | Loads: the new type has no rows | | A component type removed | Loads: its slices are skipped (its data is dropped) | | A component type renamed or moved to another namespace | Loads with `[NinoFormerName("Old.Namespace.Name")]` on it; skipped without | | Fields of a raw unmanaged component changed (added, removed, retyped, renamed) | `InvalidDataException` | | Members appended to a `VersionTolerant` or `Keyed` component | Loads: the new members keep their defaults | | A change the component's Nino format does not allow (its slice no longer reads to the last byte) | `InvalidDataException` | | A component switched between raw rows and `[NinoType]` | `InvalidDataException` | | Two types of the process with one id (one name, or a former name that is another's) | `InvalidDataException`: rename one | | Bytes that are not a save, or a damaged one | `InvalidDataException` | So a component whose shape will change is a `[NinoType]` from its first save. It stays unmanaged (a column of values, no references), and Nino writes it value by value instead of as one block: ```csharp [NinoType(format: NinoFormat.VersionTolerant)] public partial record struct Rank(int Tier, int Points) : IComponent; // the first build // A later build renames it and appends a member: old saves load, Season is 0 in their rows. [NinoType(format: NinoFormat.VersionTolerant), NinoFormerName("Rank")] public partial record struct Standing(int Tier, int Points, int Season) : IComponent; ``` A raw component cannot change shape. Add a new component type instead: a build that has both loads the old save, a system converts the old component into the new one, and a later build drops the old type. ```csharp public record struct Crafting(int Recipe, int Progress) : IComponent; // saved as raw rows public record struct Workshop(int Recipe, int Progress, int Queue) : IComponent; // the new shape // Runs in the build that knows both types: every loaded Crafting becomes a Workshop. // A later build deletes Crafting and this system. public class UpgradeCrafting : EcsSystem { [ForEach] static void Upgrade(Entity player, in Crafting old) { player.SetWorkshop(old.Recipe, old.Progress, Queue: 0); player.RemoveCrafting(); } } ``` ```csharp try { restarted.Load(output.WrittenSpan); } catch (InvalidDataException) { // a component changed since this save: the world is as it was before the call } ``` ### Components in plugins The id lookup is process-wide. While a plugin's old version and its new one are both loaded, their types share ids and a load refuses them as ambiguous. Unload the old version first (the [hot reload](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#hot-reload) order: save, `RemoveTypes`, unload, load the new version, `Load`), or keep the components you save in an assembly that is never reloaded, such as a contracts assembly shared by the host and the plugins. ## Full example Two players, one following the other, and a clock: the world is saved into a buffer and loaded into a new world, as a restarted process would do. Put the files in a console project that references EasyEcs ([declare the components](https://ecs.xgamedev.net/en/docs/guide/saves#declare)) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; using Nino.Core; // Unmanaged: saved as raw rows, one block per column. public record struct Position(float X, float Y) : IComponent; // An EntityId keeps its meaning: a load keeps every id and version. public record struct Follows(EntityId Leader) : IComponent; // Managed (a string): Nino writes it, so it is a partial [NinoType]. [NinoType] public partial record struct PlayerName(string Value) : IComponent; // Singletons are saved too. public record struct Clock(long Tick) : ISingletonComponent; ``` **Program.cs** ```csharp using EasyEcs; using Nino.Core; using var world = new World(); world.SetClock(Tick: 1234); var alice = world.CreateEntity(new PlayerName("alice"), new Position(3, 4)); world.CreateEntity(new PlayerName("bob"), new Position(5, 6), new Follows(alice.Id)); // Entities, components and singletons, into a buffer that can be reused for the next save. var output = new NinoArrayBufferWriter(); world.Save(output); // Another world, as a restarted process would make it. using var restarted = new World(); restarted.Load(output.WrittenSpan); Console.WriteLine($"clock: {restarted.Clock.Tick}"); foreach (var item in restarted.Query()) { Console.WriteLine($"{item.Entity.Id} {item.PlayerName.Value} at ({item.Position.X}, {item.Position.Y})"); } foreach (var item in restarted.Query()) { var leader = restarted.GetEntity(item.Follows.Leader); Console.WriteLine($"{item.PlayerName.Value} follows {leader.PlayerName.Value}"); } ``` It prints: ```text clock: 1234 0v1 alice at (3, 4) 1v1 bob at (5, 6) bob follows alice ``` The new world has the same ids, the managed names came back through Nino, the singleton clock kept its tick, and Bob's `Follows` still names Alice without any rewriting. ## How to use it fast | Instead of | Do | Why | | ------------------------------------------------------ | ------------------------------------------------------------------- | ----------------------------------------------------------------- | | A new buffer per save | One `NinoArrayBufferWriter`, `ResetWrittenCount()` before each save | Save allocates nothing once its buffers are large enough | | Another `IBufferWriter` | `NinoArrayBufferWriter` | Written directly, without the copy from the world's buffer | | A new world per load | `Load` into the same world | Its rows are reused: nothing allocated once warm | | Managed components where values would do | Unmanaged components (ids, numbers, fixed arrays) | Raw rows are one block per column; Nino encodes value by value | | `[NinoType]` on unmanaged components that never change | Raw rows for those, `[NinoType]` where the shape will change | A raw column is one copy | | Your own serializer over a `Query` | `Save` / `Load` | Ids, versions, buffers, disabled values and singletons come along | 100,000 entities in two tables, saved into a reused buffer and loaded back (`SnapshotBenchmark`): | Case | Mean | vs baseline | Allocated | | ---- | ------- | ----------- | --------- | | Save | 262 μs | — | 0 B | | Load | 1.00 ms | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Size:** for unmanaged components, the rows themselves (padding bytes cleared, so equal worlds save equal bytes), plus presence bits, ids and versions; managed and `[NinoType]` components as Nino writes them; each type's id once. - **Time:** O(entities × components) both ways. - **Allocation:** none on a repeated `Save` into a `NinoArrayBufferWriter`, none on a repeated `Load` into the same world; managed values a load reads are new objects. - **Not while a pass iterates:** both take the structural gate. ## Pitfalls | Mistake | What happens | Caught by | | ----------------------------------------------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | A managed component without `[NinoType]` | `Save` throws `InvalidOperationException` (no formatter) | At run time | | A `Nino.Generator` reference older than the Nino of EasyEcs | A package downgrade: remove the reference, the EasyEcs package brings the generator | Restore (`NU1605`) | | An `Entity` handle in a component | A managed column Nino cannot write | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) | | Editing the fields of a saved raw component | Old saves are refused | `[NinoType(format: NinoFormat.VersionTolerant)]` from the first save, or a new component type | | Renaming a component or moving its namespace | Old saves load without it | `[NinoFormerName]` with the old full name | | Old and new plugin versions loaded at once | Ambiguous names: `InvalidDataException` | Unload the old version first | | Saving or loading from another thread | Races with the owner thread | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) | ## Compared with other libraries Friflo writes JSON (`EntitySerializer`), DefaultEcs has a binary serializer that creates a new world each time, and Arch saves through a separate package. 10,000 units with a position and a stock, saved and loaded back: **Save and load 10,000 units** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | SaveLoad | 146 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Json | 20.8 ms | 143× | 6.52 MB | | DefaultEcs | Binary | 4.33 ms | 30× | 4.37 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Related - [Migration and unload](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload): `SaveEntities`, `LoadEntities`, `MoveEntities` and hot reload. - [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots): In-memory copies for rollback. - [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers): Lists saved with their elements. - [Sample: SaveLoad](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/SaveLoad): A world to a file and back, a group to another world, verified step by step. --- # Migration and unload > Move a player and what it owns to another world or server with SaveEntities and MoveEntities, and hot-reload game logic with a collectible AssemblyLoadContext. URL: https://ecs.xgamedev.net/en/docs/guide/migration-and-unload Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/migration-and-unload.md A player walks through a portal into another zone's world, or is handed to another server. Their entity, their items and their pets must arrive together, still pointing at each other. `SaveEntities` / `LoadEntities` carry such a group through bytes, `MoveEntities` copies it straight into another world of the thread, and both rewrite the `EntityId`s inside the group to the new entities. A long-running server also replaces its game logic without a restart: `RemoveTypes` takes a plugin's systems and components out of a world, so its collectible `AssemblyLoadContext` can unload and a new version can load the saved data. ## When to use it > **Use it for** > > - **Zone or map changes** between worlds of one thread: `MoveEntities`. > - **Handing a player to another server**, or storing an offline player: `SaveEntities` / `LoadEntities`. > - **A record** of part of an entity, such as an actor's balance without its connection, loaded onto the entity it > already has: a `ComponentSet` and `LoadEntitiesInto` ([records](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records)). > - **Hot reload** of game logic in a server that must not restart: `RemoveTypes`. > **Skip it for** > > Moving a whole world: [`Save` / `Load`](https://ecs.xgamedev.net/en/docs/guide/saves) keeps every id. Entities that change "zone" inside one > world: a [group](https://ecs.xgamedev.net/en/docs/guide/groups) or a component value is enough. Reloading types that are not in a collectible > context: the default context never unloads. A record of every component of an entity that does not exist yet: > `SaveEntities` without a set and `LoadEntities` create it. ## How to use it ### A group through bytes `SaveEntities(output, ids)` writes the listed entities and their components (stale ids and repeats are skipped; no singletons). `LoadEntities(bytes, handles)` creates them in another world, in this or another process, with new ids, and writes their handles in save order. ```csharp using Nino.Core; public record struct Sword(int Damage) : IComponent; // Indexed by its owner: a hero's pets are found without a scan of every pet. public record struct Pet(EntityId Owner) : IComponent, IIndexed { EntityId IIndexed.Key => Owner; } ``` ```csharp var hero = world.CreateEntity(new Health(100)); world.CreateEntity(new Sword(10), new ChildOf(hero)); world.CreateEntity(new Pet(hero), new Health(20)); // Collect the group: the hero, what hangs on it, what points at it. var group = new List { hero.Id }; foreach (var part in world.Descendants(hero)) group.Add(part.Id); // children, grandchildren and so on foreach (var pet in world.PetIndex.Find(hero.Id)) group.Add(pet.Id); // the index, not a scan of every Pet var bytes = new NinoArrayBufferWriter(); world.SaveEntities(bytes, group.ToArray()); // the group only using var otherServer = new World(); var arrived = new Entity[group.Count]; int created = otherServer.LoadEntities(bytes.WrittenSpan, arrived); // new ids, links rewritten ``` `Descendants` walks depth first and lists each entity before its children, so the group holds every parent ahead of what hangs on it: the order `MoveEntities` wants, since it destroys the originals last first and a child then goes before its parent. `Children` lists one level only. A `ChildOf` cycle makes the walk throw `InvalidOperationException`. Find what points at the hero (pets, followers) through an index on the field, as above, or through a [relation](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#relations): a query that tests every `Pet` grows with the world, not with the group. ### A group to another world of the thread `MoveEntities(target, ids, moved)` does the same between two worlds of the thread, without encoding: rows are copied, ids rewritten, then the originals are destroyed. `moved` receives the new handles in order (`default` for a skipped id). ```csharp using var nextZone = new World(); var moved = new Entity[group.Count]; int count = world.MoveEntities(nextZone, group.ToArray(), moved); // hero, sword and pet leave this world ``` - The originals are destroyed with their children, so move a [hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy#moving) together. - Cleanup components stay on the destroyed originals, for their systems to release. - Both worlds must be owned by the calling thread; moving a world into itself is refused (`ArgumentException`). ### A record of what persists An actor's entity holds runtime state next to what persists: a connection, timers, a cache, and a bank balance that must survive a restart. A `ComponentSet` names the components of the record, `SaveEntities(output, ids, set)` writes those only (the others need no Nino formatter), and `LoadEntitiesInto(bytes, entities)` puts them onto entities that exist already, such as the one the actor got when it was activated, before its record came back from the database. Use a record when only part of an entity outlives the process (the rest is rebuilt by the code that activates it), or when the entity is created before its data arrives. Build the set once, in a `static readonly` field, from the components that persist; save into a reused `NinoArrayBufferWriter` and store the written bytes wherever the data lives (a database row, a file, a message to another server). ```csharp public record struct Bank(long Gold) : IComponent; public record struct Connection(int Socket) : IComponent; // runtime only: never saved public static class Records { public static readonly ComponentSet Persistent = ComponentSet.Create().With(); // built once } ``` ```csharp var actor = world.CreateEntity(new Bank(500), new Connection(7)); var record = new NinoArrayBufferWriter(); world.SaveEntities(record, [actor.Id], Records.Persistent); // Bank only // Later, maybe in another process: the actor is activated, then its record arrives. var activated = world.CreateEntity(new Connection(9)); world.LoadEntitiesInto(record.WrittenSpan, [activated]); // Bank added, Connection kept ``` ```csharp var restored = world.CreateEntity(new Connection(10)); // Instead of the call above: the record restored without counting as a change. world.LoadEntitiesInto(record.WrittenSpan, [restored], markWritten: false); ``` - The i-th saved entity loads onto the i-th entity given; the counts must match and every entity must be alive in this world, or the call throws `ArgumentException` before changing anything. - Each entity moves table at most once, whatever the number of components it receives. Components the record holds are added or replace the entity's values; the others stay. - Indexes, groups and change tracking follow as with `Set`. A disabled component arrives disabled with its value. - A load is a write: `[Changed]` methods see the loaded components. When the record only restores what was there (an actor coming back from its database), pass `markWritten: false`: every component the record holds ends with no change tick, also one that replaces a default (from a prefab, say), so a system that saves or replicates changed components does not send the record straight back. Components the record does not hold keep their ticks. - The price of `markWritten: false`: the restored components are invisible to every `[Changed]` method and `Since` filter until code writes them. A replicator that sends changes to clients must send the full state itself to a client that has not seen the entity yet. - So one prefab per kind of actor serves both cases: a new actor keeps the prefab's defaults as its first state (written, so the next save stores them), and a restored one gets its record over them (not written). The [Actors sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/Actors) does this. - `SaveEntities` with a set also writes an entity that holds none of the set's components, as an empty entry, so the i-th saved entity still matches the i-th entity given. - `EntityId` fields are rewritten as below, onto the entities given; a `ChildOf` whose parent is not in the record is not set. - `LoadEntitiesInto` is a structural change: owner thread only ([EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014)), not while a pass iterates (`InvalidOperationException`), never in a parallel method ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010)), and in a `[ForEach]` method only when it takes `Entity` or `World` ([EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013)). - A framework that learns its types at run time builds the set by `Type`: ```csharp public static class RuntimeRecords { public static readonly ComponentSet Persistent = ComponentSet.Create().With(typeof(Bank)); } ``` ### How ids are rewritten The generator records where every `EntityId` field of a component or buffer element is, private fields and nested structs included. When a group arrives: | An `EntityId` field that named | Becomes | | -------------------------------------------- | --------------------------------------------------- | | An entity of the group | The id of its new entity | | Any other entity (it stayed behind) | `EntityId.Null` | | The parent of a `ChildOf` that stayed behind | The `ChildOf` is removed: the entity is a root here | Ids inside collections (a `List` in a component) are not rewritten. Indexes and groups learn the arrivals, and their tracked components count as written. ### Unloading a plugin's types `world.RemoveTypes(assembly)` (or `RemoveTypes(context)` for every assembly of an `AssemblyLoadContext`) removes everything of the plugin from the world: its systems (their `OnDestroy` runs), singletons, indexes and groupings, and its components from every entity. The entities stay, without those components. Tables that had such a column are dropped with every cache naming them, so the world holds no reference to the assembly. Once every world removed it, the collectible context can unload; when it does, EasyEcs forgets the types' save ids and reuses their component bits once no live world mentions them. ### Hot reload Saves record types by id, so a reload keeps the plugin's data: save, remove the types, unload, load the new version, load the save. ```csharp using System.Buffers; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Loader; public sealed class PluginContext() : AssemblyLoadContext("plugin", isCollectible: true); public static class Plugins { public static Assembly Reload(World world, PluginContext old, PluginContext next, string path) { var saved = new ArrayBufferWriter(); world.Save(saved); // the plugin's components too, by type id world.RemoveTypes(old); // its systems, singletons and components leave old.Unload(); // collected once nothing else roots it var plugin = next.LoadFromAssemblyPath(path); RuntimeHelpers.RunModuleConstructor(plugin.ManifestModule.ModuleHandle); // registers its types for Load world.Load(saved.WrittenSpan); // the new version's components take the values return plugin; // then add its systems to the world } } ``` The order matters: while both versions are loaded their types share ids, and a load would refuse them as ambiguous. Keep the components the host owns (positions, ids) in an assembly that is never reloaded, and hold no references of your own to the old version's types (systems, plugin objects), or the context cannot be collected. A [snapshot](https://ecs.xgamedev.net/en/docs/guide/snapshots) taken before `RemoveTypes` cannot be restored after it. The [HotReload sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/HotReload) runs the whole cycle and checks that the old context was collected and that the plugin's data carried over. ## Full example A hero with a sword (and a gem in the sword) and a pet walks into another zone: the group is collected with `Descendants` and the pet index, moved with `MoveEntities`, and the pet still points at its hero. Then an actor's bank comes back from an earlier run as a record, loaded with `markWritten: false`, and a `[Changed]` saver finds nothing to save until a deposit. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Health(int Value) : IComponent; // Hangs on the hero through ChildOf; a gem hangs on the sword. public record struct Sword(int Damage) : IComponent; public record struct Gem(int Bonus) : IComponent; // Points at its owner. Indexed by the owner, so the owner's pets are found without a scan. public record struct Pet(EntityId Owner) : IComponent, IIndexed { EntityId IIndexed.Key => Owner; } // What persists of an actor, and what does not. public record struct Bank(long Gold) : IComponent, ITrackChanges; public record struct Connection(int Socket) : IComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Writes to storage the banks written since its last run. public class SaveChangedBanks : EcsSystem { [ForEach, Changed] static void Save(Entity actor, in Bank bank) { Console.WriteLine($"saving {actor.Id}: {bank.Gold} gold"); } } ``` **Groups.cs** ```csharp using EasyEcs; public static class Groups { // The hero, what hangs on it (each parent before its children), and its pets. public static EntityId[] Collect(World world, Entity hero) { var group = new List { hero.Id }; foreach (var part in world.Descendants(hero)) { group.Add(part.Id); } foreach (var pet in world.PetIndex.Find(hero.Id)) { group.Add(pet.Id); } return group.ToArray(); } } ``` **Records.cs** ```csharp using EasyEcs; public static class Records { // The components of an actor that outlive the process. Built once. public static readonly ComponentSet Persistent = ComponentSet.Create().With(); } ``` **Program.cs** ```csharp using EasyEcs; using Nino.Core; // Two zones of one process. The next zone has entities already, so ids differ there. using var zone = new World(); using var nextZone = new World(); nextZone.CreateEntity(new Health(50)); nextZone.CreateEntity(new Health(50)); var hero = zone.CreateEntity(new Health(100)); var sword = zone.CreateEntity(new Sword(10), new ChildOf(hero)); zone.CreateEntity(new Gem(3), new ChildOf(sword)); zone.CreateEntity(new Pet(hero.Id), new Health(20)); // The hero walks through a portal: the group moves, its ids are rewritten. EntityId[] group = Groups.Collect(zone, hero); var moved = new Entity[group.Length]; zone.MoveEntities(nextZone, group, moved); for (int i = 0; i < group.Length; i++) { Console.WriteLine($"{group[i]} -> {moved[i].Id}"); } Entity pet = moved[^1]; Console.WriteLine($"pet owner: {pet.Pet.Owner}, hero: {moved[0].Id}"); Console.WriteLine($"left behind: {zone.EntityCount} entities"); // A record: an actor's bank, saved by an earlier run without its connection. using var earlier = new World(); var saved = earlier.CreateEntity(new Bank(500), new Connection(7)); var record = new NinoArrayBufferWriter(); earlier.SaveEntities(record, [saved.Id], Records.Persistent); using var world = new World(); world.AddSystem(); // The actor is activated without a Bank: the record adds it, not marked as written. var actor = world.CreateEntity(new Connection(9)); world.LoadEntitiesInto(record.WrittenSpan, [actor], markWritten: false); Console.WriteLine($"update after the load ({actor.Bank.Gold} gold):"); world.Update(); actor.SetBank(Gold: 650); Console.WriteLine("update after a deposit:"); world.Update(); ``` It prints: ```text 0v1 -> 2v1 1v1 -> 3v1 2v1 -> 4v1 3v1 -> 5v1 pet owner: 2v1, hero: 2v1 left behind: 0 entities update after the load (500 gold): update after a deposit: saving 0v1: 650 gold ``` Every entity of the group gets a new id in the next zone (two ids were taken there), the pet's `Owner` names the hero's new id, and nothing stays behind. The restored bank is not saved again on the update after the load; the deposit is. ## How to use it fast | Instead of | Do | Why | | ------------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------- | | `SaveEntities` + `LoadEntities` between worlds of one process | `MoveEntities` | Rows copied, no encoding | | A new buffer per migration | One `NinoArrayBufferWriter`, `ResetWrittenCount()` each time | No allocation once it is large enough | | Many small migrations of one entity | One migration of the whole group | A save's fixed cost (the types by id) is paid once | | `SaveEntities` of whole entities when only some components persist | A `ComponentSet` | The runtime components are not written, and need no formatter | | A `ComponentSet` built for every save | One `static readonly` set | Each `With` copies the set | | A reload that rebuilds the world | `RemoveTypes`, then `Load` | The host's entities and components stay where they are | 10 players with 99 items each, moved to another world and back through bytes and in memory, and one entity of four components through bytes, and a record of two of its components saved and loaded onto an entity that holds the others (`MigrationBenchmark`); a plugin with a tracked and an indexed component on every player, a singleton, a system and an index, removed with `RemoveTypes` (`UnloadBenchmark`): | Case | Mean | vs baseline | Allocated | | -------------- | ------- | ----------- | --------- | | SaveAndLoad | 222 μs | 1.00× | 0 B | | Move | 165 μs | 0.74× | 0 B | | SaveAndLoadOne | 2.22 μs | 0.01× | 0 B | | SaveRecord | 104 ns | 0.00× | 0 B | | LoadRecord | 722 ns | 0.00× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Players | Mean | vs baseline | Allocated | | ----------- | ------- | ------- | ----------- | --------- | | RemoveTypes | 10000 | 247 μs | — | 2.95 KB | | RemoveTypes | 100000 | 2.38 ms | — | 2.95 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **Migration:** O(entities × components); the rewrite of ids is a lookup per `EntityId` field. - **Allocation:** none for `SaveEntities`, `LoadEntities`, `LoadEntitiesInto` and `MoveEntities` once their buffers are large enough. - **`RemoveTypes`:** O(entities with such components + tables + cached queries); it allocates, and it is cold: run it between updates, not in a tick. - **Steady state:** nothing. The unload support costs no time in worlds that never call `RemoveTypes`. ## Pitfalls | Mistake | What happens | Caught by | | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------ | | Moving a parent without its children | The children are destroyed with the original | Collect the group with `Descendants` | | Collecting the group with `Children` only | Grandchildren are left out, and destroyed with their parent | `Descendants` walks every level | | `EntityId`s in a `List` inside a component | Not rewritten: they name entities of the old world | Use fields, a buffer or a relation | | An `Entity` handle in a component | Not saved, not rewritten | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) | | Loading the new plugin before unloading the old one | Ambiguous type ids: `InvalidDataException` | The reload order above | | Keeping references to the old plugin's systems | The context is never collected | Drop them after `RemoveTypes` | | `RemoveTypes` during an update or a pass | `InvalidOperationException` | At run time | | Restoring a snapshot taken before `RemoveTypes` | `InvalidOperationException` | At run time | | Migrating from another thread | Both worlds belong to their owner thread | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) | | A component that persists left out of the record's set | Not saved: the loaded entity keeps its own value, or has none | Build the set from the persisting components, in one place | | A record loaded with `LoadEntities` | New entities beside the live ones | `LoadEntitiesInto` with the live entities | | `LoadEntitiesInto` with another number of entities than the save holds, or a stale one | `ArgumentException`; nothing changes | One live entity per saved entity, in save order | | A restored record seen as changed | A `Changed` saver or replicator sends it straight back | `markWritten: false` | | Replicating only `[Changed]` rows after a `markWritten: false` load | A client that has not seen the entity never gets the restored values | Send the full state to a new client | ## Related - [Saves](https://ecs.xgamedev.net/en/docs/guide/saves): The whole world as bytes, versioning and Nino. - [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy): Collect a group with `Descendants`. - [Sample: SaveLoad](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/SaveLoad): `SaveEntities`, `LoadEntities` and `MoveEntities`, verified step by step. - [Sample: HotReload](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/HotReload): A collectible plugin unloaded and reloaded with its data. --- # Threading and parallel systems > How EasyEcs uses every core without locks on hot paths: one owner thread per world, parallel stages of non-conflicting systems and parallel [ForEach]. URL: https://ecs.xgamedev.net/en/docs/guide/threading Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/threading.md A server has many cores and a lot of entities. EasyEcs spreads the work three ways, none of which needs a lock on a hot path: **one world per thread** (a world per zone or map, each owned by its thread), **parallel systems** (inside one update, systems whose access does not conflict run at once) and **parallel `[ForEach]`** (one heavy method split into chunks of rows). The generator writes each system's read and write sets from its parameters, so the scheduler, not discipline, decides what may run together, and the analyzer rejects what could race. ## When to use it > **Use it for** > > One world per thread for a server with several zones, maps or matches. `ParallelSystems` for several heavy, > independent systems in one world. `[ForEach(Parallel = true)]` for one method over tens of thousands of rows. > **Skip it for** > > Several threads of your own changing one world: structural changes belong to its owner thread (EECS014 reports the > ones it sees). Parallel systems or methods over a few hundred rows: the hand-off to the thread pool costs more than > the work. ## How to use it ### Terms: process, world, owner thread | Term | Meaning | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Process** | Your server. It holds any number of worlds; they share nothing but type indices. | | **World** | One isolated set of entities, components, singletons and systems (`new World()`). | | **Owner thread** | The thread that calls `world.Update()` and touches the world's data. One at a time per world. | | **Parallel stage** | Inside one `Update()`, systems with no order and no conflict between them, run on thread-pool threads with the owner taking part. Ownership does not change. | ### Recommended: one world per thread Worlds share nothing, so a server that splits its entities over several worlds, each owned by one thread, needs no synchronization at all. ```mermaid flowchart LR T1[Thread 1] --> W1[World: zone 1] T2[Thread 2] --> W2[World: zone 2] T3[Thread N] --> W3[World: zone N] ``` ```csharp public static class Zones { // A world per thread: each thread owns its world, nothing is shared. public static Thread[] Start(World[] worlds) { var threads = new Thread[worlds.Length]; for (int i = 0; i < worlds.Length; i++) { var zone = worlds[i]; // one variable per iteration threads[i] = new Thread(() => { for (int t = 0; t < 1_000; t++) zone.Update(); }); threads[i].Start(); } return threads; } } ``` The [MultiWorld sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/MultiWorld) runs this layout and prints entity-updates per second. To move a player to a zone of another thread, hand it across as bytes: the source's owner writes the group with [`SaveEntities`](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#save-entities) and posts the bytes to a queue the target's owner drains, which calls `LoadEntities`. `MoveEntities` is only for two worlds owned by the same thread. ### Order of systems `Update()` runs systems in registration order, with each system that carries `[UpdateBefore]` / `[UpdateAfter]` moved just before or after `T`. Systems never call each other: a system that consumes what another produces is registered after it or says `[UpdateAfter]`. Structural changes apply at once, so a later system of the same update already sees an entity an earlier one created, destroyed or tagged: there are no command buffers to play back. Whatever runs in parallel, the result of an update equals running the systems one by one in that order. ### Parallel systems With `WorldOptions.ParallelSystems = true`, systems with no order and no conflict between them run at the same time. Each system's access comes from its `[ForEach]` parameters: | `[ForEach]` parameter | Declares | | --------------------------------------------------------------- | ----------------------------------------------------------------- | | `ref T` component or singleton | writes `T` | | `in T` component or singleton | reads `T` | | `[With]`, `[Without]`, `[WithAny]` | nothing (filters read presence, which no parallel system changes) | | `[Changed]`, `[Removed]` | reads `T` (its change ticks) | | `Entity` or `World`, an instance method, an `OnUpdate` override | runs alone | | no `[ForEach]` method at all | runs alone | Two systems conflict when one writes something the other reads or writes, or when either runs alone. A system goes to the stage after the latest one holding a system it must follow (by an ordering, or by an earlier system it conflicts with). Stages run one after another; the systems of a stage run at once. ```csharp public record struct Body(float X, float Y, float Vx, float Vy) : IComponent; public record struct Vitals(int Health, int Max) : IComponent; public record struct Alarms(int Count) : ISingletonComponent; public class MoveBodies : EcsSystem // writes Body { [ForEach] static void Move(ref Body b) { b.X += b.Vx; b.Y += b.Vy; } } public class RegenerateHealth : EcsSystem // writes Vitals { [ForEach] static void Regenerate(ref Vitals v) => v.Health = Math.Min(v.Health + 1, v.Max); } public class LowHealthAlarm : EcsSystem // reads Vitals: conflicts with RegenerateHealth { [ForEach] static void Count(in Vitals v, ref Alarms alarms) { if (v.Health < 10) alarms.Count++; } } ``` ```mermaid flowchart LR subgraph S1 [stage 1: at once] M[MoveBodies] R[RegenerateHealth] end subgraph S2 [stage 2] A[LowHealthAlarm] end S1 --> S2 ``` ```csharp using var parallel = new World(new WorldOptions { ParallelSystems = true }); parallel.AddSingleton(); parallel.AddSystem(); parallel.AddSystem(); parallel.AddSystem(); parallel.Update(); // stage 1 on two threads, then stage 2 ``` The runner allocates nothing: the calling thread works through a stage with up to `MaxDegreeOfParallelism - 1` reusable thread-pool work items. Lower `MaxDegreeOfParallelism` when several worlds or IO threads share the cores: ```csharp using var zone = new World(new WorldOptions { ParallelSystems = true, MaxDegreeOfParallelism = 4 }); ``` The first exception of a stage is rethrown on the calling thread after the stage; with `WorldOptions.SystemErrors = SystemErrorPolicy.Disable`, a failing system is switched off with its exception in `system.Error` instead. ### Parallel `[ForEach]` methods `[ForEach(Parallel = true)]` splits one method's rows into chunks across threads. It must make no structural change, run per entity and write no singleton ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010)): ```csharp public record struct Regen(int PerTick) : ISingletonComponent; public class RegenerateAll : EcsSystem { [ForEach(Parallel = true), Without] static void Regenerate(ref Health hp, in Regen regen) => hp.Value += regen.PerTick; // reads the singleton only } ``` Parallel systems and parallel methods compose: inside a parallel stage, a parallel method whose runner is busy with another system's method runs on its own thread instead of waiting. ### Input from other threads A world has one owner thread, and EasyEcs adds no cross-thread queue of its own: structural changes are immediate on that thread, so there is nothing to defer. Input from other threads (network, timers, a database) goes through a queue you own, and a system on the owner thread turns it into data: ```csharp using System.Collections.Concurrent; public record struct MoveRequest(int PlayerId, float X, float Y); // a message, not a component public record struct MoveIntent(int PlayerId, float X, float Y) : IComponent; public sealed class ReceiveMoves(ConcurrentQueue inbox) : EcsSystem { private readonly ConcurrentQueue _inbox = inbox; // filled by the network threads protected override void OnUpdate() { while (_inbox.TryDequeue(out var move)) World.CreateEntity(new MoveIntent(move.PlayerId, move.X, move.Y)); // input becomes data } } ``` Register it with `world.AddSystem(new ReceiveMoves(inbox))` before the systems that consume `MoveIntent`. The queue's type, bound and back-pressure are your choice. Keep the queue in a `readonly` field of the system that drains it ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007) allows it), not in a singleton: `World.Save` writes every singleton, and a managed queue would need a formatter. The [GameLoop sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/GameLoop) drains a mailbox from a network thread this way. ### What the world synchronizes | Operation | Safety | | --------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Structural changes, systems and singletons added or removed, `Capture` / `Restore`, `Save` / `Load` | Owner thread only, one at a time. A plain owner flag (no atomic instruction): one started while another runs, or while the structure is frozen (a parallel stage, a parallel `[ForEach]`, a batch job, an `INoStructuralChanges` pass), throws `InvalidOperationException` instead of tearing the tables. | | Query matching, `Has`, `Get` lookups | Lock-free over immutable, copy-on-write table lists. The first use of a query shape takes a compare-and-swap gate once. | | A singleton a system adds with `GetOrAddSingleton()` / `GetOrAddX()` | The same gate: systems of one stage may add it at once. | | Component and singleton values | Not synchronized, by design: the owner thread or the scheduler decides who touches them. | | Value indexes, and the unlinking done by destroys and removals | Owner thread only while the world has an index. | What catches a change made off the owner thread: | Where the change comes from | Caught by | | --------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | A `[ForEach]` method without `Entity` or `World` changing structure through a handle it holds | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) at compile time; the runtime throws in a parallel stage | | A system of a parallel stage, or a parallel job, changing structure through a helper | The runtime: the structure is frozen, every structural change throws | | A lambda handed to `Task.Run`, `Parallel.*`, `ThreadPool`, `new Thread` or `new Timer` changing a world the code around it also changes | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) at compile time | | Your own threads in any other way | Nothing reliable: hand the change to the owner as data | Every structural call counts here, including the less obvious ones: `entity.Run<…>(ref job)` (a job may change structure) and `LoadEntitiesInto` belong to the owner thread too, and the analyzer treats them as structural ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010), [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014)). ## Full example A hundred thousand units steer towards a target, move and regenerate: the steering method splits its rows over several threads, and the regeneration system shares a stage with it because the two touch different components. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent; // Where every unit heads. public record struct Target(float X, float Y) : ISingletonComponent; ``` **Systems.cs** ```csharp using EasyEcs; // Points every velocity at the target. // Parallel = true splits the rows into chunks on several threads: each call reads // its own row and the singleton, and writes only its own row. public class SteeringSystem : EcsSystem { [ForEach(Parallel = true)] static void Steer(in Position position, ref Velocity velocity, in Target target) { float dx = target.X - position.X; float dy = target.Y - position.Y; // The + 1 keeps the length above zero when a unit stands on the target. float length = MathF.Sqrt(dx * dx + dy * dy) + 1; velocity = new Velocity(dx / length, dy / length); } } // Writes only Health, which SteeringSystem does not touch: the two can run in the same stage. public class RegenerateSystem : EcsSystem { [ForEach] static void Regenerate(ref Health health) { health.Value = Math.Min(health.Value + 1, 100); } } // Writes Position, which SteeringSystem reads: it waits for SteeringSystem to finish. public class MoveSystem : EcsSystem { [ForEach] static void Move(ref Position position, in Velocity velocity) { position = new Position(position.X + velocity.X, position.Y + velocity.Y); } } ``` **Program.cs** ```csharp using EasyEcs; // ParallelSystems lets systems with no conflict between them share a stage. using var world = new World(new WorldOptions { ParallelSystems = true }); world.SetTarget(X: 500, Y: 500); world.AddSystem(); world.AddSystem(); world.AddSystem(); var units = new Entity[100_000]; world.CreateEntities(units, new Position(0, 0), new Velocity(0, 0), new Health(50)); // Update is still one call on this thread: the threads it uses are done when it returns. for (int i = 0; i < 10; i++) { world.Update(); } Position at = units[0].Position; Console.WriteLine($"unit 0 at ({at.X:F2}, {at.Y:F2}) with {units[0].Health.Value} hp"); ``` It prints: ```text unit 0 at (7.06, 7.06) with 60 hp ``` The result is the same as running the three systems one by one in registration order: a parallel stage never changes what an update computes, only how many threads compute it. ## How to use it fast - **Prefer worlds to parallel stages.** Worlds on their own threads scale with no hand-off at all; a stage pays a thread-pool hand-off per update. - **Turn `ParallelSystems` on for heavy systems only**, ones that iterate thousands of entities. - **Split by data, not by method.** Two systems that write different components run together; one that writes everything runs alone. - **Read with `in`.** A `ref` that only reads declares a write, and a write conflicts ([EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) reports it). One world of 100,000 entities, and the same entities in four worlds on four threads (`WorldSimulationBenchmark`, `MultiWorldBenchmark`): 1.72 ms per tick in one world, 924 μs for the four worlds together. BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Four independent systems over 100,000 entities, sequential and parallel (`ParallelSystemsBenchmark`), and one method over 100,000 rows, sequential and parallel (`ParallelForEachBenchmark`): | Case | Parallel | Mean | vs baseline | Allocated | | ---- | -------- | ------ | ----------- | --------- | | Tick | False | 420 μs | — | 0 B | | Tick | True | 295 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Parallel | Mean | vs baseline | Allocated | | --------- | -------- | ------- | ----------- | --------- | | Tick | False | 1.68 ms | — | 0 B | | EntityJob | False | 1.92 ms | — | 0 B | | Tick | True | 884 μs | — | 0 B | | EntityJob | True | 896 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **One world, one thread:** no locks, no atomics on hot paths; a structural change checks and sets a plain flag. - **A parallel stage:** a hand-off to reusable thread-pool work items, nothing allocated; the `ParallelSystemsBenchmark` table above shows what it saves on heavy systems. - **A parallel method:** the same runner, over chunks of rows; the calling thread always takes part. - **Off:** `ParallelSystems` is off by default, and a world that never uses it pays nothing for it. ## Pitfalls | Mistake | What happens | Caught by | | ---------------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------ | | A structural change inside a parallel method | Chunks on other threads would tear the tables | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) | | A `ref` singleton in a parallel method | Chunks race on one value | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) | | Changing a collection through an `in` parameter | Scheduled as a read: races with parallel readers | [EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) | | A structural change through a held handle in a method that takes no `Entity` | The system shares a stage it should not | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | | `Task.Run(() => world.CreateEntity(...))` beside the owner | Two threads change one world | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) | | A `ref` parameter that only reads | Declares a write: fewer systems run together | [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) | ## Compared with other ECS libraries | Library | Order of systems | Systems in parallel | How conflicts are avoided | | ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- | | **EasyEcs** | Registration order, `[UpdateBefore]` / `[UpdateAfter]` | Systems with no order and no conflict; one method's rows in chunks | Access generated from `ref` / `in`; the analyzer rejects parallel methods that could race | | Arch | Your call order (Arch.System: group order) | Within one query (`ParallelQuery`) | You keep query bodies independent | | Friflo.Engine.ECS | `SystemRoot` / `SystemGroup` order | Within one query (`RunParallel`) | You keep query bodies independent | | DefaultEcs | `SequentialSystem` order | `ParallelSystem` (all children at once), per-set runners | You put only independent systems in a `ParallelSystem` | | Bevy (Rust) | Ambiguous unless ordered | Any systems whose access does not conflict | Access read from parameter types | | Unity DOTS | `UpdateBefore` / `UpdateAfter` in groups | Jobs | Read/write handles and the job safety system | EasyEcs takes the access-based model of Bevy and Unity DOTS, and keeps the order total and deterministic. Measured against the parallel runners of the others: **Four independent systems over 100,000 entities, sequential and parallel** | Library | Parallel | Mean | vs EasyEcs | Allocated | | ---------- | -------- | ------ | ---------- | --------- | | EasyEcs | False | 395 μs | 1.00× | 0 B | | DefaultEcs | False | 471 μs | 1.19× | 0 B | | EasyEcs | True | 370 μs | 1.00× | 0 B | | DefaultEcs | True | 405 μs | 1.09× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **100,000 agents steering on all cores** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------------- | ------ | ---------- | --------- | | EasyEcs | Parallel | 766 μs | 1.00× | 0 B | | Friflo.Engine.ECS | QueryJob | 754 μs | 0.98× | 0 B | | Arch | InlineParallelQuery | 685 μs | 0.89× | 0 B | | DefaultEcs | ParallelRunner | 854 μs | 1.11× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Related - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): Parameters, ordering, groups and parallel methods. - [Analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer): EECS010, EECS011, EECS013 and EECS014 in detail. - [Migration and unload](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload): Moving entities between worlds. - [Sample: MultiWorld](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/MultiWorld): One world per thread, no locks. --- # Hosting a C# ECS in .NET services > Host EasyEcs in ASP.NET Core or a Worker for game servers, simulations and real-time backends: one owner runs the tick and bounded channels carry requests. URL: https://ecs.xgamedev.net/en/docs/guide/hosting Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/hosting.md An ECS-powered game server, simulation or real-time backend can host EasyEcs in ASP.NET Core or a Worker Service: request handlers, sockets and timers run on the thread pool, while a world takes structural changes from one thread at a time. Give the world one owner, a hosted service that builds it, runs its tick and saves it when the host stops, and let everything else talk to it through a channel. EasyEcs provides the ECS world, not network transport or a complete application framework. It needs no hosting package for this pattern: the host and channel are a few classes of your own. ## When to use it > **Use it for** > > A game server, simulation or matchmaker inside ASP.NET Core, a Worker Service or any app built on > `Microsoft.Extensions.Hosting`, with HTTP endpoints, health checks and metrics next to the world. > **Skip it for** > > A console tool, a benchmark or a test: `new World()` and a loop are enough ([getting started](https://ecs.xgamedev.net/en/docs/getting-started), > [testing](https://ecs.xgamedev.net/en/docs/guide/testing)). Do not share one world between request handlers behind a lock: a lock around > every request serializes the server anyway, and reads without it race with the tick. ## How to use it Everything that is not the world's owner reaches it through two doors: a channel of requests the tick drains, and an immutable status the tick publishes. ```mermaid flowchart LR H[HTTP handlers, sockets] -->|requests| C[Channel] C --> L[World loop: Update] L -->|replies| H L -->|publishes| S[Status] S -->|reads| H G[Host] -->|start, stop| L ``` ### Give the world one owner One object owns the world, and only its loop touches it. A `PeriodicTimer` sets the tick; every `world.Update()` runs all systems synchronously and returns before the next `await`. ```csharp public sealed class WorldLoop(World world) { private readonly World _world = world; public async Task RunAsync(CancellationToken stop) { using var timer = new PeriodicTimer(TimeSpan.FromMilliseconds(50)); // 20 ticks per second try { while (await timer.WaitForNextTickAsync(stop)) _world.Update(); } catch (OperationCanceledException) { // the host is stopping } } } ``` After an `await`, the loop may resume on another thread-pool thread. That is allowed: the owner is whoever changes the world, one at a time, and each `await` orders one tick after the other. Use a dedicated thread (`new Thread`, or `Task.Factory.StartNew` with `TaskCreationOptions.LongRunning`) when the tick needs steadier timing than a busy thread pool gives. ### Start and stop with the host A `BackgroundService` runs the loop for the life of the app. On Ctrl+C or `SIGTERM` the host cancels the token and waits for `ExecuteAsync` to finish, up to `HostOptions.ShutdownTimeout` (30 seconds by default), so a final save fits there. ```csharp public sealed class WorldService(WorldLoop loop) : BackgroundService { protected override Task ExecuteAsync(CancellationToken stoppingToken) => loop.RunAsync(stoppingToken); } ``` ```csharp using EasyEcs; var builder = Host.CreateApplicationBuilder(args); var world = new World(); builder.Services.AddSingleton(new WorldLoop(world)); builder.Services.AddHostedService(); builder.Build().Run(); ``` These two blocks are skipped by the docs' compile check only because it does not reference `Microsoft.Extensions.Hosting`; in a Worker Service or ASP.NET Core project they build as they are. An exception that leaves `Update()` (a system threw, under the default `SystemErrorPolicy.Throw`) ends `ExecuteAsync`, and the host stops: the process fails fast and the platform restarts it. With `new WorldOptions { SystemErrors = SystemErrorPolicy.Disable }` the failing system is switched off instead and the tick goes on; report its `system.Error` from a health check ([errors](https://ecs.xgamedev.net/en/docs/guide/systems#errors)). ### Hand requests to the world A request is a message, not a component. Handlers write it into a bounded `Channel`; a system drains the channel at the start of each tick and turns each message into data. A request that needs an answer carries a `TaskCompletionSource` the system completes: ```csharp using System.Threading.Channels; public readonly record struct SpawnRequest(float X, float Y, TaskCompletionSource Reply); public sealed class ReceiveSpawns(ChannelReader requests) : EcsSystem { private readonly ChannelReader _requests = requests; // a dependency: allowed (EECS007) protected override void OnUpdate() { while (_requests.TryRead(out var request)) { var unit = World.CreateEntity(new Position(request.X, request.Y)); request.Reply.TrySetResult(unit.Id); // answer with an id, never a handle } } } ``` Create each reply with `TaskCreationOptions.RunContinuationsAsynchronously`. Without it, `TrySetResult` runs the handler's continuation inline, on the world's thread, in the middle of the tick. Answer with an `EntityId` or a copy of the values: an `Entity` handle used by the handler later would touch the world from another thread. Bound the channel (`Channel.CreateBounded`) so a world that falls behind slows its callers down (`BoundedChannelFullMode.Wait`) or refuses them (`DropWrite`, `TryWrite` returning false) instead of growing without limit. The [threading guide](https://ecs.xgamedev.net/en/docs/guide/threading#input-from-other-threads) shows the same pattern with a plain `ConcurrentQueue`. The reader lives in a `readonly` field of the system, not in a singleton: `World.Save` writes every singleton, and a channel has no formatter. On shutdown, complete the writer (`requests.Writer.TryComplete()`) after the last tick, then answer what is still in the channel. A handler that writes after that gets a `ChannelClosedException` at once instead of a reply that never comes ([full example](https://ecs.xgamedev.net/en/docs/guide/hosting#full-example), `Arena.RunAsync`). A request about an entity that exists already carries its `EntityId`. The system finds the entity and runs a job on it with [`entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity): one lookup for all the job's components, and a filter that rules out a dead unit. `Run` returns `false` when the entity is gone, fails the filter or lacks a component, which is the reply: ```csharp using System.Threading.Channels; public readonly record struct HealRequest(EntityId Unit, int Amount, TaskCompletionSource Reply); public struct Heal : IForEachEntity { public int Amount; public static int Writes => 1; public void Execute(Entity unit, ref Health health) => health.Value += Amount; } public sealed class ReceiveHeals(ChannelReader requests) : EcsSystem { private static readonly QueryFilter Alive = QueryFilter.Create().Without(); // built once private readonly ChannelReader _requests = requests; protected override void OnUpdate() { while (_requests.TryRead(out var request)) { var heal = new Heal { Amount = request.Amount }; bool healed = World.TryGetEntity(request.Unit, out var unit) && unit.Run(ref heal, Alive); // false: gone, dead or no Health request.Reply.TrySetResult(healed); } } } ``` ### Let handlers read without a round trip Handlers never read the world directly: component values are not synchronized, and the tick moves and rewrites rows while a handler would read them. Instead, a system copies what handlers may see into an immutable object and publishes it with one atomic write; handlers read the latest copy without waiting for a tick: ```csharp public sealed record ArenaStatus(long Tick, int Units); public sealed class StatusBoard { private ArenaStatus _current = new(Tick: 0, Units: 0); public ArenaStatus Current => Volatile.Read(ref _current); public void Publish(ArenaStatus status) => Volatile.Write(ref _current, status); } public sealed class PublishStatus(StatusBoard board) : EcsSystem { private readonly StatusBoard _board = board; public override int UpdateInterval => 20; // once a second at 20 Hz protected override void OnUpdate() => _board.Publish(new ArenaStatus(World.UpdateCount, World.Count())); } ``` `UpdateInterval` keeps the copy (and its allocation) off most ticks. A read that must see the state of this very tick goes through the channel as a request with a reply, like a write. ### Load at start, save at stop Load the last save before the first tick, then add only the singletons the save did not hold: `Load` replaces the world's singletons, and `AddSingleton` would reset one that was loaded. Save after the loop ends, into a temporary file moved over the old one, so a crash during the write never leaves half a save. When systems save or replicate `[Changed]` rows, load with `markWritten: false`, so the first tick does not send the loaded world again ([restart](https://ecs.xgamedev.net/en/docs/guide/saves#restart)): ```csharp using Nino.Core; public static class Persistence { public static void LoadOrStart(World world, string path) { if (File.Exists(path)) world.Load(File.ReadAllBytes(path)); if (!world.HasClock) world.AddSingleton(); } public static void Save(World world, string path) { var output = new NinoArrayBufferWriter(); world.Save(output); File.WriteAllBytes(path + ".tmp", output.WrittenSpan); File.Move(path + ".tmp", path, overwrite: true); } } public record struct Clock(long Tick) : ISingletonComponent; ``` For autosaves while the server runs, call `Save` on the owner between two ticks, then hand the bytes to another thread for the disk write: the world is only needed while it encodes. What a save holds and what survives a code change are in [saves](https://ecs.xgamedev.net/en/docs/guide/saves#versioning). ### Several worlds, health and metrics - **Several worlds:** one loop per world, each its own owner (one hosted service per zone, or one service that starts a loop per world). They share nothing, so they need no locks ([one world per thread](https://ecs.xgamedev.net/en/docs/guide/threading#recommended-one-world-per-thread)). Lower `WorldOptions.MaxDegreeOfParallelism` when `ParallelSystems` worlds and Kestrel share the cores. - **Metrics:** with `WorldOptions.MeasureSystems`, read `system.Stats` (`Runs`, `Last`, `Average`) for each system of `world.Systems` on the loop, between two updates, and publish the numbers with the status ([measuring systems](https://ecs.xgamedev.net/en/docs/guide/systems#measuring-systems)). - **Health:** under `SystemErrorPolicy.Disable`, a system with a non-null `Error` is switched off; publish that list and let the health check report it. ### Deploy - **Native AOT:** `true` publishes the world and its systems as a native executable: `EasyEcs.Core` is marked `IsAotCompatible` and the generated code calls your methods directly, and the publish has no warnings. A generic system closed only by another assembly needs `MakeGenericType`, which Native AOT cannot do ([FAQ](https://ecs.xgamedev.net/en/docs/faq#native-aot)). ASP.NET Core has AOT rules of its own (`WebApplication.CreateSlimBuilder`, JSON source generation): see Microsoft's [Native AOT guide for ASP.NET Core](https://learn.microsoft.com/aspnet/core/fundamentals/native-aot). - **Containers:** `docker stop` and Kubernetes send `SIGTERM`, which the host turns into the shutdown above. Give the container a grace period longer than the final save. - **No IO in systems:** a system that awaits or blocks stalls the whole tick. Systems hand IO out as data (a request in a queue, bytes in an outbox) and the host does it outside `Update()`. ## Full example An ASP.NET Core server with one arena: `POST /units` spawns a unit and answers with its id, `GET /status` reads the copy the world publishes once a second, and the world is saved on shutdown and loaded on the next start. Create it with `dotnet new web -n Arena`, add `dotnet add package EasyEcs`, and replace `Program.cs` with these files. **Components.cs** ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; // The tick and its length, kept in the world: systems read it and a save keeps it. public record struct Clock(long Tick, float DeltaTime) : ISingletonComponent; ``` **Messages.cs** ```csharp using EasyEcs; // What a request handler asks of the world: a message, not a component. // The world's thread answers through Reply. public readonly record struct SpawnRequest(float X, float Y, TaskCompletionSource Reply); // What request handlers read: an immutable copy the world's thread publishes. public sealed record ArenaStatus(long Tick, int Units); // The one object both sides share: the world's thread writes it, any thread reads it. public sealed class StatusBoard { private ArenaStatus _current = new(Tick: 0, Units: 0); public ArenaStatus Current => Volatile.Read(ref _current); public void Publish(ArenaStatus status) => Volatile.Write(ref _current, status); } ``` **Systems.cs** ```csharp using System.Threading.Channels; using EasyEcs; // Turns the requests that arrived since the last tick into units, on the world's thread. public sealed class ReceiveSpawns(ChannelReader requests) : EcsSystem { // A dependency, not state: readonly fields are allowed (EECS007). private readonly ChannelReader _requests = requests; protected override void OnUpdate() { while (_requests.TryRead(out var request)) { var unit = World.CreateEntity(new Position(request.X, request.Y), new Velocity(1, 0)); request.Reply.TrySetResult(unit.Id); } } } public class MovementSystem : EcsSystem { [ForEach] static void Move(ref Position position, in Velocity velocity, in Clock clock) { position = new Position( position.X + velocity.X * clock.DeltaTime, position.Y + velocity.Y * clock.DeltaTime); } } public class ClockSystem : EcsSystem { protected override void OnUpdate() => World.Clock.Tick++; } // Copies what request handlers may read, once a second at 20 ticks per second. public sealed class PublishStatus(StatusBoard board) : EcsSystem { private readonly StatusBoard _board = board; public override int UpdateInterval => 20; protected override void OnUpdate() { _board.Publish(new ArenaStatus(World.Clock.Tick, World.Count())); } } ``` **Arena.cs** ```csharp using Nino.Core; using System.Threading.Channels; using EasyEcs; // Owns the world: builds it, loads the last save, runs the tick, saves on the way out. // Only RunAsync touches the world, one tick after another: that makes it the owner. public sealed class Arena : IDisposable { public const int TicksPerSecond = 20; private readonly World _world = new(); private readonly Channel _requests; private readonly string _savePath; public Arena(Channel requests, StatusBoard board, string savePath) { _requests = requests; _savePath = savePath; // Load replaces entities, components and singletons; systems are not saved. if (File.Exists(savePath)) { _world.Load(File.ReadAllBytes(savePath)); } if (!_world.HasClock) { _world.SetClock(Tick: 0, DeltaTime: 1f / TicksPerSecond); } // Registration order is the tick's order. _world.AddSystem(new ReceiveSpawns(requests.Reader)); _world.AddSystem(); _world.AddSystem(); _world.AddSystem(new PublishStatus(board)); } public async Task RunAsync(CancellationToken stop) { using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1.0 / TicksPerSecond)); try { // Each tick may resume on another thread-pool thread: still one at a time. while (await timer.WaitForNextTickAsync(stop)) { _world.Update(); } } catch (OperationCanceledException) { // The host is stopping. } // No more requests: a handler that writes now gets ChannelClosedException at once. _requests.Writer.TryComplete(); // Requests that arrived too late get an answer too. while (_requests.Reader.TryRead(out var late)) { late.Reply.TrySetCanceled(); } Save(); } private void Save() { var output = new NinoArrayBufferWriter(); _world.Save(output); // Write a temporary file and move it over the old save: a crash never leaves half a save. string temporary = _savePath + ".tmp"; File.WriteAllBytes(temporary, output.WrittenSpan); File.Move(temporary, _savePath, overwrite: true); } public void Dispose() => _world.Dispose(); } ``` **ArenaService.cs** ```csharp // The host starts the loop with the app and cancels it on shutdown (Ctrl+C, SIGTERM). public sealed class ArenaService(Arena arena) : BackgroundService { protected override Task ExecuteAsync(CancellationToken stoppingToken) => arena.RunAsync(stoppingToken); } ``` **Program.cs** ```csharp using System.Threading.Channels; using EasyEcs; var builder = WebApplication.CreateBuilder(args); // Bounded: when the world falls behind, handlers wait instead of filling memory. var requests = Channel.CreateBounded( new BoundedChannelOptions(1024) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait }); var board = new StatusBoard(); builder.Services.AddSingleton(board); builder.Services.AddSingleton(new Arena(requests, board, savePath: "arena.sav")); builder.Services.AddHostedService(); var app = builder.Build(); // A write: hand it to the world's thread and wait for its answer. app.MapPost("/units", async (float x, float y, CancellationToken aborted) => { // RunContinuationsAsynchronously: this handler resumes on the thread pool, // never inside the world's tick. var reply = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await requests.Writer.WriteAsync(new SpawnRequest(x, y, reply), aborted); EntityId id = await reply.Task.WaitAsync(aborted); return new { id.Index, id.Version }; }); // A read: the copy the world published, no trip to its thread. app.MapGet("/status", (StatusBoard status) => status.Current); app.Run(); ``` Run it with `dotnet run --urls http://localhost:5000`. In a second terminal, spawn two units and read the status; then stop the server with Ctrl+C, start it again, and repeat: ```text $ curl -X POST "localhost:5000/units?x=0&y=0" {"index":0,"version":1} $ curl -X POST "localhost:5000/units?x=5&y=5" {"index":1,"version":1} $ curl localhost:5000/status {"tick":60,"units":2} $ curl -X POST "localhost:5000/units?x=0&y=0" {"index":2,"version":1} $ curl -X POST "localhost:5000/units?x=5&y=5" {"index":3,"version":1} $ curl localhost:5000/status {"tick":125,"units":4} ``` The second run starts from the save: the two units of the first run are still there (four units in all), new ids continue after theirs, and the clock goes on from where it stopped instead of starting at zero. The status is at most a second old, and reading it never waits for the world. ## How to use it fast | Instead of | Do | Why | | ----------------------------------------- | ----------------------------------------------------- | ------------------------------------------------- | | A lock around the world for every request | A channel the tick drains | One owner, no lock on the tick | | A request per read | A status the tick publishes | Reads cost a volatile load, not a tick of latency | | Publishing every tick | `UpdateInterval` on the publishing system | The copy is made only when it is due | | Writing the save file on the tick | `Save` on the owner, the file write on another thread | The tick waits for encoding only | | One world for every zone | One world and loop per zone | Worlds share nothing and scale across cores | The tick itself is the cost that matters. A world of 100,000 entities updates in 1.72 ms per tick, allocating 0 B (`WorldSimulationBenchmark`), so a 20 Hz tick leaves the rest of each 50 ms to request handlers. BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **The loop:** one timer and one `Update()` per tick; nothing allocated by EasyEcs. - **A request:** a channel write and read, plus the reply's `TaskCompletionSource` (allocated per request, on the handler's side). - **A status:** one immutable object per publish, read with a volatile load. - **Shutdown:** one `Save` and one file write, within `HostOptions.ShutdownTimeout`. ## Pitfalls | Mistake | What happens | Caught by | | ---------------------------------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A handler calls `world.CreateEntity` or `entity.Set` | Two threads change one world | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) for lambdas handed to `Task.Run` and the like; the runtime when two changes collide; otherwise nothing | | A handler reads components directly | Values torn or stale while the tick moves rows | Nothing: publish a copy | | A reply without `RunContinuationsAsynchronously` | The handler runs inside the tick, on the world's thread | Code review | | Replying with an `Entity` handle | The handler later touches the world from its own thread | Reply with an `EntityId` or copied values | | `AddSingleton` after `Load` | The loaded singleton is reset | Check `HasSingleton()` (or the generated `HasX`) first | | An unbounded channel | A world that falls behind fills memory | Use `Channel.CreateBounded` | | The channel left open on shutdown | A handler that writes after the last drain, or waits on a full channel, never gets its reply | `requests.Writer.TryComplete()` after the last tick, then answer what is left | | `await` or blocking IO in a system | The whole tick waits | Hand the IO to the host as data | ## Related - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): The owner thread, input from other threads and parallel systems. - [Saves](https://ecs.xgamedev.net/en/docs/guide/saves): What `Save` writes, and which code changes a save survives. - [Testing systems](https://ecs.xgamedev.net/en/docs/guide/testing): The same world, built in a test and checked after one update. - [Sample: GameLoop](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/GameLoop): A fixed tick, a mailbox from a network thread and replication of what changed. --- # Testing systems > Test EasyEcs systems with a world per test: arrange entities and singletons, call Update, assert on data. Shared setup, errors, allocation budgets, saves. URL: https://ecs.xgamedev.net/en/docs/guide/testing Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/testing.md A system has no dependencies to mock: it reads and writes data in its world, and it never calls another system. So a test builds a small world of its own, adds the entities and singletons the system needs, calls `world.Update()` and checks the data the system left. The same holds for a whole tick: run the server's systems in the server's order and assert on the outcome. ## When to use it > **Use it for** > > Every system's rules (damage, expiry, death), the order of a whole tick, what a save keeps, and a budget of zero > bytes allocated per tick. Tests run in milliseconds: a world is cheap to create and dispose. > **Skip it for** > > Timing: a test that asserts how long a tick takes is flaky; measure with BenchmarkDotNet instead > ([performance](https://ecs.xgamedev.net/en/docs/performance)). Testing EasyEcs itself (queries, structural changes): the library's own > tests cover it, and your tests should state your game's rules. ## How to use it The examples use NUnit, as the `dotnet new easyecs --tests` template does; xUnit and MSTest work the same way. The components and systems are those of the [full example](https://ecs.xgamedev.net/en/docs/guide/testing#full-example): `Health`, `Poison`, the `Dead` tag, the `Score` singleton, `PoisonSystem` and `DeathSystem`. ### Arrange, update, assert One world per test, disposed at the end. Add only the system under test and the data it needs, run one update, then read components through the handles you kept: ```csharp [Test] public void HurtsEveryTickThenWearsOff() { using var world = new World(); world.AddSystem(); var unit = world.CreateEntity(new Health(10), new Poison(DamagePerTick: 3, Ticks: 2)); world.Update(); Assert.That(unit.Health.Value, Is.EqualTo(7)); Assert.That(unit.Poison.Ticks, Is.EqualTo(1)); world.Update(); Assert.That(unit.Health.Value, Is.EqualTo(4)); Assert.That(unit.HasPoison, Is.False, "the last tick removes the poison"); } ``` Test the filters too: an entity the system must leave alone is one more `CreateEntity` and one more assertion. Every structural change applies at once, so what a system did is visible right after `Update()` returns: there is no command buffer to flush. ### Share the setup with the server Systems run in registration order. When the server and the tests each add the systems by hand, the tests can pass in an order the server never runs. Put the setup in one method that `Program.cs` and the tests both call: ```csharp public static class Battle { public static void Setup(World world) { world.AddSingleton(); world.AddSystem(); world.AddSystem(); } } [Test] public void APoisonedUnitDiesAndScores() { using var world = new World(); Battle.Setup(world); var unit = world.CreateEntity(new Health(5), new Poison(5, 3)); world.Update(); Assert.That(unit.IsDead, Is.True); Assert.That(world.Score.Kills, Is.EqualTo(1)); } ``` ### Control time and input with data A system that reads `DateTime.Now`, a random generator or a socket cannot be tested exactly. Give it a singleton instead (a clock with a tick and a step, a seed, a config) and set that singleton in the test. Input is data too: a test creates the request entities a network system would have created, or writes into the queue the input system drains ([hosting](https://ecs.xgamedev.net/en/docs/guide/hosting#requests)). - **Intervals:** a system with `UpdateInterval => 4` runs on every fourth `Update()`; call `Update()` that many times. - **Groups:** systems in `[UpdateInGroup]` run only on `world.Update()`; call it in the test as the host would. - **Change tracking:** a `[Changed]` method sees the writes made since its system last ran; write the component between two updates and assert on the second one ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking)). ### Test errors By default an exception in a system propagates out of `Update()`, so a test asserts it with `Assert.Throws`. Under `SystemErrorPolicy.Disable` the system is switched off and keeps the exception in `Error`: ```csharp // Prints the score; it reads the singleton without adding it. public class ScoreReport : EcsSystem { protected override void OnUpdate() => Console.WriteLine($"kills: {World.Score.Kills}"); } [Test] public void AMissingSingletonThrowsOutOfUpdate() { using var world = new World(); world.AddSystem(); Assert.Throws(() => world.Update()); } [Test] public void UnderDisableTheSystemIsSwitchedOff() { using var world = new World(new WorldOptions { SystemErrors = SystemErrorPolicy.Disable }); var report = new ScoreReport(); world.AddSystem(report); world.Update(); Assert.That(report.Enabled, Is.False); Assert.That(report.Error, Is.InstanceOf()); } ``` ### Hold a budget of zero bytes A tick that allocates feeds the garbage collector, and pauses follow. Assert the budget: build the world, run one update to warm up the query caches and tables, then count the bytes the next updates allocate on this thread: ```csharp [Test] public void ATickAllocatesNothing() { using var world = new World(); Battle.Setup(world); var units = new Entity[1_000]; world.CreateEntities(units, new Health(1_000_000), new Poison(1, int.MaxValue)); // The first update builds the query caches: measure the ones after it. world.Update(); long before = GC.GetAllocatedBytesForCurrentThread(); for (int i = 0; i < 100; i++) { world.Update(); } long allocated = GC.GetAllocatedBytesForCurrentThread() - before; Assert.That(allocated, Is.Zero); } ``` `GC.GetAllocatedBytesForCurrentThread()` counts this thread only: with `ParallelSystems` or parallel `[ForEach]` methods, use `GC.GetTotalAllocatedBytes(precise: true)` and keep other tests from running at the same time. A structural change into a table that does not exist yet allocates the table once, so warm up with the same kinds of changes the measured ticks make. ### Test what a save keeps Save the world, load the bytes into a new one and look for the state you care about. Entities keep their ids, so a handle found by its `EntityId` in the new world is the same entity: ```csharp [Test] public void ABattleSurvivesARestart() { using var world = new World(); Battle.Setup(world); var unit = world.CreateEntity(new Health(5), new Poison(5, 3)); world.Update(); var output = new ArrayBufferWriter(); world.Save(output); using var restarted = new World(); Battle.Setup(restarted); // After Setup: Load replaces the singletons Setup added. restarted.Load(output.WrittenSpan); var loaded = restarted.GetEntity(unit.Id); Assert.That(loaded.IsDead, Is.True); Assert.That(restarted.Score.Kills, Is.EqualTo(1)); } ``` A test like this, run against a save file kept from the previous release, also tells you when a component change would make old saves fail to load ([saves](https://ecs.xgamedev.net/en/docs/guide/saves#versioning)). ## Full example A poison that wears off, a death that scores, and five tests: two of one system alone, then one each for the whole tick, a zero-byte budget and a save. The game is a class library; the tests are an NUnit project that references it (`dotnet new nunit`, then `dotnet add reference` to the game and `dotnet add package EasyEcs`). **Components.cs** ```csharp using EasyEcs; public record struct Health(int Value) : IComponent; // Damage over time: DamagePerTick for the next Ticks ticks. public record struct Poison(int DamagePerTick, int Ticks) : IComponent; public struct Dead : IComponent; public record struct Score(int Kills) : ISingletonComponent; ``` **Systems.cs** ```csharp using EasyEcs; public class PoisonSystem : EcsSystem { [ForEach, Without] static void Hurt(Entity unit, ref Poison poison, ref Health health) { health.Value -= poison.DamagePerTick; if (--poison.Ticks == 0) { unit.RemovePoison(); } } } [UpdateAfter] public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health health, ref Score score) { if (health.Value > 0) { return; } unit.SetDead(); score.Kills++; } } // The one place that builds a battle: Program.cs and the tests both call it, // so the tests run the systems in the order the server does. public static class Battle { public static void Setup(World world) { world.AddSingleton(); world.AddSystem(); world.AddSystem(); } } ``` **BattleTests.cs** ```csharp using System.Buffers; using EasyEcs; using NUnit.Framework; public class PoisonSystemTests { [Test] public void HurtsEveryTickThenWearsOff() { using var world = new World(); world.AddSystem(); var unit = world.CreateEntity(new Health(10), new Poison(DamagePerTick: 3, Ticks: 2)); world.Update(); Assert.That(unit.Health.Value, Is.EqualTo(7)); Assert.That(unit.Poison.Ticks, Is.EqualTo(1)); world.Update(); Assert.That(unit.Health.Value, Is.EqualTo(4)); Assert.That(unit.HasPoison, Is.False, "the last tick removes the poison"); } [Test] public void LeavesTheDeadAlone() { using var world = new World(); world.AddSystem(); var corpse = world.CreateEntity(new Health(0), new Poison(3, 2)); corpse.SetDead(); world.Update(); Assert.That(corpse.Health.Value, Is.Zero); } } public class BattleTests { [Test] public void APoisonedUnitDiesAndScores() { using var world = new World(); Battle.Setup(world); var unit = world.CreateEntity(new Health(5), new Poison(5, 3)); world.Update(); Assert.That(unit.IsDead, Is.True); Assert.That(world.Score.Kills, Is.EqualTo(1)); } [Test] public void ATickAllocatesNothing() { using var world = new World(); Battle.Setup(world); var units = new Entity[1_000]; world.CreateEntities(units, new Health(1_000_000), new Poison(1, int.MaxValue)); // The first update builds the query caches: measure the ones after it. world.Update(); long before = GC.GetAllocatedBytesForCurrentThread(); for (int i = 0; i < 100; i++) { world.Update(); } long allocated = GC.GetAllocatedBytesForCurrentThread() - before; Assert.That(allocated, Is.Zero); } [Test] public void ABattleSurvivesARestart() { using var world = new World(); Battle.Setup(world); var unit = world.CreateEntity(new Health(5), new Poison(5, 3)); world.Update(); var output = new ArrayBufferWriter(); world.Save(output); using var restarted = new World(); Battle.Setup(restarted); // After Setup: Load replaces the singletons Setup added. restarted.Load(output.WrittenSpan); var loaded = restarted.GetEntity(unit.Id); Assert.That(loaded.IsDead, Is.True); Assert.That(restarted.Score.Kills, Is.EqualTo(1)); } } ``` **Battle.Tests.csproj** ```xml net10.0 enable false ``` `dotnet test --logger "console;verbosity=normal"` prints: ```text Passed ABattleSurvivesARestart [118 ms] Passed APoisonedUnitDiesAndScores [< 1 ms] Passed ATickAllocatesNothing [43 ms] Passed HurtsEveryTickThenWearsOff [2 ms] Passed LeavesTheDeadAlone [1 ms] Total tests: 5 Passed: 5 ``` The times are mostly the JIT compiling each path once. Notice the budget test: a hundred ticks of a thousand poisoned units allocate nothing once the first tick has run. ## How to use it fast | Instead of | Do | Why | | ---------------------------------- | -------------------------------------------------------------- | ---------------------------------------------- | | A world shared by all tests | A world per test, in `using` | Tests stay independent and can run in parallel | | Systems added by hand in each test | The server's own setup method | The test runs the tick's real order | | Waiting for real time | A clock singleton set by the test | Exact, and as fast as the code | | Asserting how long a tick takes | A zero-byte budget in the test, timings in BenchmarkDotNet | Allocation counts are exact; times are not | | Comparing whole worlds by hand | Counts (`world.Count()`) and the components of kept handles | One line per rule | ## What it costs - **A world:** one `new World()` and its `Dispose()`: the entity array and an empty table. - **The analyzer:** it also runs on the test project, so a test system with state or a race fails the build there too ([analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer)). - **Nothing in the game:** tests use the public API only; there is no test mode to switch on. ## Pitfalls | Mistake | What happens | Caught by | | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------- | | Forgetting a singleton the system reads (a `[ForEach]` parameter, `World.X` or `GetSingleton()`) | `Update()` throws `InvalidOperationException` naming the singleton | The test fails: call the server's setup method, or set the singleton in the test | | `AddSingleton` after `Load` in a save test | The loaded value is reset | Add singletons before `Load` | | Measuring allocations without a warm-up update | The query caches and new tables count as allocations | Warm up first | | A `ref` held across `world.Update()` | The update may move rows: the ref reads stale memory | Read through the handle after the update ([refs](https://ecs.xgamedev.net/en/docs/guide/refs-and-await)) | ## Related - [Systems](https://ecs.xgamedev.net/en/docs/guide/systems): Lifecycle, ordering, intervals, groups and errors. - [Hosting in a .NET server](https://ecs.xgamedev.net/en/docs/guide/hosting): The same setup run by a hosted service on a fixed tick. - [Saves](https://ecs.xgamedev.net/en/docs/guide/saves): What `Save` keeps and which code changes a save survives. - [Templates](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/templates): `dotnet new easyecs --tests`: a test file per system. --- # Debugging and diagnostics > Debug a running EasyEcs world: tables and memory with Describe, an entity's components in the debugger, per-system timing and the systems that failed. URL: https://ecs.xgamedev.net/en/docs/guide/diagnostics Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/diagnostics.md An entity is an id, and its data is spread over table columns, so a debugger watch on a handle shows little by itself, and a server that slows down does not say which system grew. EasyEcs answers both from data the world already has: `world.Describe()` lists the tables with their rows and bytes, `entity.Describe()` (and the debugger) shows an entity's component values, `system.Stats` times every system, and `system.Error` keeps the exception of a system that failed. ## When to use it > **Use it for** > > An admin or health endpoint of a live server (entity counts, memory per table, the slowest system, the systems > that failed), a log line when a tick runs long, a breakpoint on an entity in the IDE, and a memory report after a > load test. > **Skip it for** > > Game logic: a system that needs to know what an entity has asks with a filter or `HasX`, not with `Describe`. Every > tick: `Describe` allocates its answer, so call it on a request or a timer, not in the loop. Timing a change: > `system.Stats` shows trends on a live server; compare two versions with BenchmarkDotNet > ([performance](https://ecs.xgamedev.net/en/docs/performance#measuring)). ## How to use it ### Look at an entity `entity.Describe()` returns the entity's components as `ComponentValue`s: a boxed copy of each value, and `Enabled` false for a [disabled](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable#disable-a-component) one. A stale handle describes as nothing. In a debugger, an `Entity` shows as `Entity 1000v1` (index and version) and expands to its id, whether it is alive, and its components, read when you expand it. ```csharp var guard = world.CreateEntity(new Position(5, 5), new Health(50)); foreach (var component in guard.Describe()) Console.WriteLine(component.Enabled ? $"{component.Value}" : $"{component.Value} (disabled)"); ``` `Console.WriteLine(entity)` prints the same `Entity 1000v1`, and an `EntityId` prints as `1000v1`: what to log, and what a client sends back to name an entity. ### Look at the tables `world.Describe()` returns one `TableInfo` per table: its `Columns` (each a component `Type`, the rows `Without` it, and its `Group` in a [grouped](https://ecs.xgamedev.net/en/docs/guide/groups) world), its living `Entities`, the `Rows` in use, the `Capacity` allocated and the `Bytes` that costs. ```csharp foreach (var table in world.Describe()) { var names = new List(); foreach (var column in table.Columns) names.Add(column.Type.Name); Console.WriteLine($"[{string.Join(", ", names)}] {table.Entities} entities, {table.Bytes:N0} bytes"); } ``` What to read in it: - **Where the memory is:** `Bytes` per table, which grows with `Capacity`, not with `Entities`: a table that once held a wave keeps its rows for the next one. - **Removed components:** a column's `Without` counts the rows that removed or disabled it, since [removing keeps the row](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#storage). A large share means most entities of the table no longer have it. - **Combinations:** each distinct set of components is a table. Hundreds of small tables mean the code adds many different combinations; a [group](https://ecs.xgamedev.net/en/docs/guide/groups) splits tables on purpose. - **Holes:** `Rows` above `Entities` is a pass in progress that left holes; they close when it ends. `world.EntityCount` is the total (O(1)), and `world.Count(filter)` counts the entities a query would visit by summing table counts. ### Time each system With `WorldOptions.MeasureSystems`, every run of a system (its `OnUpdate` and its `[ForEach]` methods) is timed: `system.Stats` holds `Runs`, `Last`, `Total` and `Average`. `world.Systems` lists the systems without allocating, so a status page can show the slowest one ([measuring systems](https://ecs.xgamedev.net/en/docs/guide/systems#measuring-systems)). ```csharp public class RegenSystem : EcsSystem { [ForEach] static void Regen(ref Health health) => health.Value++; } ``` ```csharp using var measured = new World(new WorldOptions { MeasureSystems = true }); measured.AddSystem(); measured.Update(); foreach (var system in measured.Systems) Console.WriteLine($"{system.GetType().Name}: last {system.Stats.Last.TotalMicroseconds} μs"); ``` ### Find the systems that failed By default an exception a system throws leaves `Update()`. With `SystemErrors = SystemErrorPolicy.Disable`, the system is switched off instead, its exception stays in `system.Error`, and the update goes on: a failure becomes data a health check reads. Setting `Enabled = true` clears `Error` and tries the system again ([errors](https://ecs.xgamedev.net/en/docs/guide/systems#errors)). ```csharp using var guarded = new World(new WorldOptions { SystemErrors = SystemErrorPolicy.Disable }); guarded.AddSystem(); guarded.Update(); foreach (var system in guarded.Systems) if (system.Error is { } error) Console.Error.WriteLine($"{system.GetType().Name} is off: {error.Message}"); ``` ### Which thread Read diagnostics on the world's owner thread between two updates, like the [hosting guide](https://ecs.xgamedev.net/en/docs/guide/hosting#reads) publishes a status: the numbers then describe one finished tick. `world.Describe()` may also be called from another thread for a rough picture (it never corrupts the world), but a table changed at the same time may be read half-way. `entity.Describe()` and `system.Stats` belong to the owner thread. ## Full example A world of walkers and guards, with one buggy system, described after three updates. Put the files in a console project that references EasyEcs (`dotnet add package EasyEcs`) and run it with `dotnet run`. **Components.cs** ```csharp using EasyEcs; public record struct Position(float X, float Y) : IComponent; public record struct Velocity(float X, float Y) : IComponent; public record struct Health(int Value) : IComponent; public record struct Cooldown(int Ticks) : IComponent; ``` **Systems.cs** ```csharp using EasyEcs; public class MoveSystem : EcsSystem { [ForEach] static void Move(ref Position position, in Velocity velocity) { position = new Position(position.X + velocity.X, position.Y + velocity.Y); } } // A bug to find: a cooldown that ran out should be removed; this throws instead. public class CooldownSystem : EcsSystem { [ForEach] static void Tick(ref Cooldown cooldown) { cooldown.Ticks--; if (cooldown.Ticks < 0) { throw new InvalidOperationException("a cooldown went below zero"); } } } ``` **Program.cs** ```csharp using EasyEcs; var options = new WorldOptions { // Time every run of every system: system.Stats. MeasureSystems = true, // A system that throws is switched off and keeps the exception: system.Error. SystemErrors = SystemErrorPolicy.Disable, }; using var world = new World(options); world.AddSystem(); world.AddSystem(); var walkers = new Entity[1_000]; world.CreateEntities(walkers, new Position(0, 0), new Velocity(1, 0)); var guards = new Entity[200]; world.CreateEntities(guards, new Position(5, 5), new Health(50), new Cooldown(2)); // A walker that stops: its row stays, and the Velocity column counts one row without it. walkers[0].RemoveVelocity(); for (int tick = 0; tick < 3; tick++) { world.Update(); } Diagnostics.PrintTables(world); Diagnostics.PrintEntity(guards[0]); Diagnostics.PrintSystems(world); ``` **Diagnostics.cs** ```csharp using EasyEcs; // What an admin endpoint would return, printed. Cold code that allocates: call it between updates. public static class Diagnostics { public static void PrintTables(World world) { Console.WriteLine($"{world.EntityCount} entities"); foreach (var table in world.Describe()) { var columns = new List(); foreach (var column in table.Columns) { string without = column.Without > 0 ? $" ({column.Without} without)" : ""; columns.Add(column.Type.Name + without); } Console.WriteLine($" [{string.Join(", ", columns)}] {table.Entities} entities, " + $"{table.Capacity} rows allocated, {table.Bytes:N0} bytes"); } } public static void PrintEntity(Entity entity) { Console.WriteLine(entity); foreach (var component in entity.Describe()) { string state = component.Enabled ? "" : " (disabled)"; Console.WriteLine($" {component.Value}{state}"); } } public static void PrintSystems(World world) { foreach (var system in world.Systems) { string name = system.GetType().Name; string state = system.Error is { } error ? $"off: {error.Message}" : "on"; Console.WriteLine($"{name}: {system.Stats.Runs} runs, {state}"); } } } ``` It prints: ```text 1200 entities [] 0 entities, 64 rows allocated, 512 bytes [Position, Velocity (1 without)] 1000 entities, 1024 rows allocated, 24,840 bytes [Position, Cooldown, Health] 200 entities, 256 rows allocated, 6,256 bytes Entity 1000v1 Position { X = 5, Y = 5 } Cooldown { Ticks = -1 } Health { Value = 50 } MoveSystem: 3 runs, on CooldownSystem: 3 runs, off: a cooldown went below zero ``` The walker that stopped stays in its table, counted in `Velocity (1 without)`. The first table is the world's empty table, where `CreateEntity()` without components puts an entity. The guard shows the value the buggy system left, `Cooldown { Ticks = -1 }`, and `CooldownSystem` is off with its exception kept while `MoveSystem` goes on running: the third update did not stop at the bug. ## How to use it fast | Instead of | Do | Why | | ---------------------------------------------- | ---------------------------------------------- | --------------------------------------- | | `Describe()` on every tick | On a request or a timer, between updates | It allocates its answer | | `entity.Describe()` to test for a component | `HasX`, `TryGetX`, a filter | No boxing, no allocation | | A stopwatch around `world.Update()` | `MeasureSystems` and `system.Stats` | Per system, two timestamp reads per run | | A try/catch around `Update()` on a live server | `SystemErrorPolicy.Disable` and `system.Error` | The other systems keep running | Describing the battle server's world for a dashboard and one entity for a debugger (`IntrospectionBenchmark`): | Case | Mean | vs baseline | Allocated | | ------ | ------- | ----------- | --------- | | Tables | 10.6 μs | — | 25.0 KB | | Entity | 244 ns | — | 832 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What it costs - **`world.Describe()`:** O(tables + columns); allocates one `TableInfo` per table and its columns. - **`entity.Describe()`:** O(components of the entity); boxes each value. - **`MeasureSystems`:** two timestamp reads per system run when on; nothing when off. - **`SystemErrorPolicy.Disable`:** nothing until a system throws. - **The debugger view** costs nothing at run time: it is read only when a debugger asks. ## Pitfalls | Mistake | What happens | Caught by | | --------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | `Describe()` in a system or every tick | Allocations on the hot path | Code review | | Reading `Describe()` from another thread during an update | Counts of a table caught half-way through a change | Read between updates on the owner thread | | Expecting `Bytes` to drop when entities leave | Tables keep their capacity for the next wave | Read `Entities` against `Capacity` | | Leaving `SystemErrorPolicy.Disable` on in tests | A failing system is silently off and the test checks other things | Keep the default `Throw` in tests ([testing](https://ecs.xgamedev.net/en/docs/guide/testing#errors)) | | Logging `entity.Id.Index` alone | The index is reused by later entities | Log the entity or its `EntityId` (`1000v1`) | ## Related - [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#measuring-systems): Measuring systems, errors and the system list. - [Hosting in a .NET server](https://ecs.xgamedev.net/en/docs/guide/hosting#operations): Publishing health and metrics from the world's loop. - [Troubleshooting](https://ecs.xgamedev.net/en/docs/guide/troubleshooting): What an exception from EasyEcs means and how to fix it. - [Architecture](https://ecs.xgamedev.net/en/docs/architecture#storage-model): The tables, columns and rows that `Describe` reports. --- # Analyzer rules > Every EasyEcs analyzer rule, EECS002 to EECS034, with its severity, its code fix, the code it rejects and the code to write instead. URL: https://ecs.xgamedev.net/en/docs/guide/analyzer Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/analyzer.md The EasyEcs analyzer ships in the package next to the source generator, so code that breaks the [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles) does not build. The correctness rules (EECS002 to EECS024) are errors except three warnings for code that works but costs (EECS017, EECS018, EECS020). The generator skips invalid input and the analyzer reports it, so "not generated" always means "reported". The performance rules (EECS025 to EECS034) find code that works and does more than it needs, and the severity says what kind ([D29](https://ecs.xgamedev.net/en/docs/decisions#d29-performance-rules-only-where-the-cost-is-measured-and-the-fix-does-the-same)): a warning means the code costs (EECS025 to EECS032), a suggestion (Info) means the same cost written shorter (EECS033), and an error means code that cannot work (EECS034, a world update inside a system). Where a rule has one mechanical answer, the IDE offers it as a code fix (EasyEcs.CodeFixes, in the same package), and only when the result compiles. ## When to read it > **Read it for** > > A build error or warning whose id starts with `EECS`: jump to its section from the table below. Each section says > what the rule protects, the code it rejects, the fix and whether the IDE can apply it. > **Do not** > > Suppress an `EECS` error with `#pragma`: the generator skipped the method or type the rule names, so the code it > needs does not exist. The warnings can be suppressed, at the cost they describe; a suggestion (Info) shows in the > IDE only, and `dotnet_diagnostic.EECS033.severity = warning` in `.editorconfig` raises one for a whole project. ## All rules | Id | Severity | Rule | Code fix | | ------------------------------------------------------------------ | -------- | ------------------------------------------------------------------------------------------ | ------------------------------------------- | | [EECS002](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs002) | Error | Invalid `[ForEach]` parameter | `in` / `ref` for a component taken by value | | [EECS003](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs003) | Error | A `[ForEach]` method takes 1 to 9 components, or none with a `[With]` or `[Changed]` | | | [EECS004](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs004) | Error | A system's `[ForEach]` method is not generic | | | [EECS005](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs005) | Error | An instance `[ForEach]` method belongs to a system | Make it static | | [EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006) | Error | Components and singletons are structs | Make it a struct | | [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007) | Error | Systems are stateless | | | [EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008) | Error | Systems do not reference systems | | | [EECS009](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs009) | Error | A batch `[ForEach]` method takes only spans, singletons and an `EntitySpan` | | | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) | Error | A `[ForEach(Parallel = true)]` method can run on several threads | Run it on one thread | | [EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs011) | Error | A `[ForEach]` method does not change what a read-only parameter holds | Take it by `ref` | | [EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012) | Error | A `DynamicBuffer` is never copied | `in`, or `ref` with the callers | | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | Error | A `[ForEach]` method that takes no `Entity` or `World` changes no structure | | | [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014) | Error | Structural changes stay on the world's owner thread | | | [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015) | Error | An indexed component is written with `Set` | | | [EECS016](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs016) | Error | A `[Removed]` method does not require `T` | | | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) | Warning | Components store an `EntityId`, not an `Entity` | | | [EECS018](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs018) | Warning | `UpdateInterval` and `UpdatePhase` are constants | | | [EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019) | Error | Systems are not ordered in a cycle | | | [EECS020](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs020) | Warning | Systems are ordered within their group | | | [EECS021](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs021) | Error | A `[ForEach]` entry point does not collide with a method | | | [EECS022](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs022) | Error | The generated code can name a `[ForEach]` method's types | Make it internal | | [EECS023](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs023) | Error | Filters go on `[ForEach]` methods and system groups | Remove the filter | | [EECS024](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs024) | Error | `[ForEach]` is not on a local function | | | [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) | Warning | A write access only reads | `in`, `ReadOnlySpan`, `Read()` | | [EECS026](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs026) | Warning | A `[ForEach]` method uses its parameters | `[With]`, or remove the parameter | | [EECS027](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs027) | Warning | A `[ForEach]` method takes what it looks up on every row | | | [EECS028](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs028) | Warning | Code that runs every update does not allocate | | | [EECS029](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs029) | Warning | An instance `[ForEach]` method uses its system | Make it static | | [EECS030](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs030) | Warning | A structural change over a query is one bulk call | The bulk call | | [EECS031](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs031) | Warning | Entities created in a counted loop are created together, or reserved | `CreateEntities`, `EnsureCapacity` | | [EECS032](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs032) | Warning | The world counts and filters | `Any`, `Count` | | [EECS033](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs033) | Info | A generated member says it shorter | The generated member | | [EECS034](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs034) | Error | A system does not run a world update | | ## EECS002 **Invalid `[ForEach]` parameter.** Error. Code fix: adds `in` or `ref` to a component or singleton taken by value. Every parameter must be a `ref` / `in` / `ref readonly` struct implementing `IComponent` or `ISingletonComponent`, a `Span` / `ReadOnlySpan` of an `IComponent` struct, a `Maybe` of one (an optional component), an `Entity`, or the `World`. A [`[ForEach]` method outside a system](https://ecs.xgamedev.net/en/docs/guide/systems#foreach-outside-systems) may also take values of any other type: its generated entry point takes them from the caller. ```csharp public class MoveSystem : EcsSystem { [ForEach] static void Move(ref Position p, float dt) { } // a system's method gets no caller's value } ``` Pass components and singletons by `ref` (write) or `in` / `ref readonly` (read), and turn other values into data: ```csharp public record struct DeltaTime(float Seconds) : ISingletonComponent; // the value becomes a singleton public class MoveSystem : EcsSystem { [ForEach] static void Move(ref Position p, in Velocity v, in DeltaTime dt) { p.X += v.X * dt.Seconds; p.Y += v.Y * dt.Seconds; } } ``` ## EECS003 **Invalid component count.** Error. No code fix. A `[ForEach]` method takes between 1 and 9 components (singletons, `Entity`, `World` and a runner's other values do not count; a `Maybe` does), or none when a `[With]` (else a `[Changed]`) names the component to query. `[Removed]` names none: the entities it selects no longer have `T`, so the method also needs a component parameter or a `[With]`. ```csharp public class CorpseCleanupSystem : EcsSystem { [ForEach] static void Remove(Entity e) => e.Destroy(); // which entities? no component names them } ``` Name the component with a filter. With no component at all, use `OnUpdate`; with more than 9, move the extra requirements to `[With]` or split the method: ```csharp public class CorpseCleanupSystem : EcsSystem { [ForEach, With] // the filter names what to query static void Remove(Entity e) => e.Destroy(); } ``` ## EECS004 **Generic `[ForEach]` method in a system.** Error. No code fix. A system runs its `[ForEach]` methods itself, once per update, so a generic method would get no type arguments. Generic systems are fine (each closed type is a system of its own), and so are generic `[ForEach]` methods outside systems, whose entry points take the type arguments from the caller. ```csharp public class ClampSystem : EcsSystem { [ForEach] static void Clamp(ref T value) where T : struct, IComponent { } // which T? } ``` Make the system generic instead of the method: ```csharp public interface IClamped { int Value { get; set; } } public class ClampSystem : EcsSystem where T : struct, IComponent, IClamped // AddSystem>() { [ForEach] static void Clamp(ref T value) => value.Value = Math.Max(value.Value, 0); } ``` ## EECS005 **Instance `[ForEach]` method outside a system.** Error. Code fix: makes the method static, when its body uses no instance member. A `[ForEach]` method of a type that is no `EcsSystem` gets a generated entry point that takes the world (`Physics.Move(world)`), and there is no instance to call the method on. ```csharp public class Physics { [ForEach] void Move(ref Position p, in Velocity v) { p.X += v.X; p.Y += v.Y; } // on which Physics? } ``` Make it static, or move it into a system: ```csharp public static class Physics // Physics.Move(world) runs it once over the world { [ForEach] public static void Move(ref Position p, in Velocity v) { p.X += v.X; p.Y += v.Y; } } ``` ## EECS006 **ECS data must be a struct.** Error. Code fix: changes the class to a struct, for a class declared once, with no base class and no member a struct cannot have (`protected`, `virtual`, `abstract`, a finalizer). Components and singletons are stored by value in columns. Interfaces may extend the markers; classes may not implement them. ```csharp public class Wallet : IComponent { public int Gold; } ``` ```csharp public record struct Wallet(int Gold) : IComponent; ``` ## EECS007 **Systems must be stateless.** Error. No code fix. A system has a mutable field, a settable auto-property or a field-like event (static ones included), or a member writes a primary-constructor parameter (a hidden field). State in a system is invisible to other systems, queries and saves, it is lost or duplicated when the system is removed or added again, and a static one is shared by every world. `readonly` fields (dependencies, reusable scratch buffers), `init`-only properties and computed properties are allowed. ```csharp public class SpawnSystem : EcsSystem { private int _spawned; // state no one else can see or save protected override void OnUpdate() => _spawned++; } ``` Move per-entity state into a component and per-world state into a [singleton](https://ecs.xgamedev.net/en/docs/guide/singletons): ```csharp public record struct Spawned(int Count) : ISingletonComponent; public class SpawnSystem : EcsSystem { protected override void OnUpdate() => World.GetOrAddSpawned().Count++; } ``` ## EECS008 **Systems must not reference systems.** Error. No code fix. A field, auto-property, event or primary-constructor parameter of a system has a system type (an array of systems or a type argument included), or a system looks another one up with `World.GetSystem()`. Systems that call each other are coupled: neither can be removed, reordered or tested alone. `GetSystem` is for tools, tests and the code that hosts the world. ```csharp public class KillSystem : EcsSystem { } public class ScoreSystem(KillSystem kills) : EcsSystem { private readonly KillSystem _kills = kills; // the two can no longer change apart } ``` Write the data the other system reads (a component or a singleton) and order the two ([ECS principles, rule 3](https://ecs.xgamedev.net/en/docs/ecs-principles#3-systems-never-reference-systems)): ```csharp public record struct Score(int Deaths) : ISingletonComponent; public class KillSystem : EcsSystem { [ForEach, Without] static void Kill(Entity e, in Health hp) { if (hp.Value <= 0) e.SetDead(); } } [UpdateAfter] // it reads the Dead that KillSystem wrote public sealed class ScoreSystem : EcsSystem { // One pass destroys the corpses and says how many there were: each is counted once. protected override void OnUpdate() => World.GetOrAddScore().Deaths += World.DestroyEntities(); } ``` ## EECS009 **Batch `[ForEach]` mixes spans and per-entity parameters.** Error. No code fix. A method that takes component spans receives whole runs of rows, so a per-entity parameter (a `ref` / `in` component, an `Entity`) has no single value for the call, and the `World` could change rows while the spans point into them. An `EntitySpan` without component spans has no run to describe. ```csharp public class DriftAllSystem : EcsSystem { [ForEach] static void Drift(Span p, in Velocity v) { } // v has no single value for a run of rows } ``` Take every component as a span (`Span` to write, `ReadOnlySpan` to read), singletons besides, and an `EntitySpan` for the run's entities; or write a per-entity method: ```csharp public class DriftAllSystem : EcsSystem { [ForEach] static void Drift(Span p, ReadOnlySpan v) // element i of both spans is one entity { for (int i = 0; i < p.Length; i++) { p[i].X += v[i].X; p[i].Y += v[i].Y; } } } ``` ## EECS010 **`[ForEach(Parallel = true)]` cannot run on several threads.** Error. Code fix: removes `Parallel = true`. A parallel method runs chunks of rows on several threads at once, so it must make no structural change (static, no `World`, its `Entity` used only to read: `Id`, `Has`, `Get`, ...; not `entity.Run`, which does the owner's pass bookkeeping and whose job may change structure), run per entity (not a batch method) and write no singleton (a `ref` singleton would race between chunks). ```csharp public class KillSystem : EcsSystem { [ForEach(Parallel = true)] static void Kill(Entity e, in Health hp) { if (hp.Value <= 0) e.SetDead(); } // a structural change } ``` Take singletons as `in`, move structural changes into a sequential system that reacts to data the parallel one writes, or drop `Parallel = true`: ```csharp public record struct Regen(int PerTick) : ISingletonComponent; public class RegenSystem : EcsSystem { [ForEach(Parallel = true), Without] static void Regenerate(ref Health hp, in Regen regen) => hp.Value += regen.PerTick; // reads the singleton only } ``` ## EECS011 **Write through a read-only parameter.** Error. Code fix: takes the parameter by `ref` (a `ReadOnlySpan` becomes a `Span`); none for a singleton of a parallel method, since a `ref` singleton there is EECS010. A `[ForEach]` method takes a component or singleton as `in` (or a component as `ReadOnlySpan`) and changes data it holds by reference: it calls a mutating method on a collection (`Add`, `Remove`, `Clear`, `Insert`, `Push`, `Enqueue`, `Sort`, ...), assigns an element (`grid.Cells[i] = x`) or a member of a class it holds (`holder.Owner.Gold++`). The compiler allows it because only the reference is read-only, but the write is scheduled as a read (parallel systems that read the same data race with it) and never stamped, so `[Changed]` systems and value indexes miss it. ```csharp public record struct Grid(List Cells) : ISingletonComponent; public class GridSystem : EcsSystem { [ForEach] static void Mark(in Position p, in Grid grid) => grid.Cells.Add((int)p.X); // 'in', but written } ``` ```csharp public record struct Grid(List Cells) : ISingletonComponent; public class GridSystem : EcsSystem { [ForEach] static void Mark(in Position p, ref Grid grid) => grid.Cells.Add((int)p.X); // ref: scheduled as a write } ``` Calls that return a new value (`string`, immutable and frozen collections) are reads. The rule sees changes made directly on the parameter's members; a reference copied into a local, or changed inside a method of your own class, is not followed. Collections in components are allowed; [ECS principles, rule 8](https://ecs.xgamedev.net/en/docs/ecs-principles#8-choose-how-to-hold-a-collection) says when to prefer entities. ## EECS012 **`DynamicBuffer` held by value.** Error. Code fix: adds `in`, or `ref` together with each caller's argument when every caller passes a variable; none for an override or an interface's method, whose signature is shared. A [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) refers to its list, so a copy of the value refers to the same list: writes through the copy are never stamped as changed, and storing the copy gives a second entity (or a snapshot) the same list. The rule reports a `DynamicBuffer` field or property, a by-value parameter or return, a local that is not a `ref` local, an assignment of an existing buffer, and an existing buffer passed to `Set`, `CreateEntity` or another generic method that stores it. ```csharp public record struct Loot(int Item); ``` ```csharp public static class Bags { public static void Share(Entity player, Entity other) { var bag = player.Read>(); // a copy other.Set(player.Read>()); // two entities, one list } } ``` Reach the buffer through its entity: `ref` / `in` parameters, `ref var bag = ref entity.Get>()`, `entity.Read>()`. A new component value is `new DynamicBuffer()` (or `default`), which holds no list; a [prefab](https://ecs.xgamedev.net/en/docs/guide/prefabs) gets its elements with `SetBuffer(…)` or the generated `SetLoot(…)`: ```csharp public static class Bags { public static int Items(Entity player) => player.Read>().Count; // read through the entity public static void Give(Entity player, Loot loot) { ref var bag = ref player.Get>(); // a ref local: a tracked write bag.Add(loot); } public static Entity Spawn(World world) => world.CreateEntity(new DynamicBuffer()); // a new, empty buffer } ``` ## EECS013 **Structural change in a `[ForEach]` method that promises none.** Error. No code fix. A `[ForEach]` method that is static and takes no `Entity` or `World` (or uses its `Entity` only to read) cannot change structure as far as the generator can see, so it walks the rows without re-checking storage after each call, and the system shares a [parallel stage](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems) with other systems. A structural change made anyway, through a handle or a world kept elsewhere, breaks both: the pass keeps refs into rows that moved, and a change inside a parallel stage throws. The rule reports a call to a structural member of `Entity` (`Set`, `Remove`, `Destroy`, `GetOrAdd`, `Clone`, `Disable`, `Enable`, `AddRelation`, `RemoveRelation`, `Run` (its job may change structure), and the generated `SetX`, `GetOrAddX`, `RemoveX`) or `World` (`CreateEntity`, `CreateEntities`, `Instantiate`, `DestroyEntities`, `SetAll`, `RemoveAll`, `DisableAll`, `EnableAll`, `Load`, `LoadEntities`, `LoadEntitiesInto`, `MoveEntities`, `GroupBy`, `RemoveTypes`, singletons, systems, `Update`, `Capture`, `Restore`, ...) in such a method. A world the method creates itself (`new World()` in a local) is its own. ```csharp public record struct Target(EntityId Id) : IComponent; public struct Doomed : IComponent; // a tag public static class Arena { public static readonly World Main = new(); } ``` ```csharp public class SpawnEffects : EcsSystem { [ForEach] static void Spawn(in Position p) => Arena.Main.CreateEntity(p); // no Entity or World parameter } ``` Take the `Entity` or the `World` as a parameter and make the change through it (the system then runs alone, with a pass that notices the change), or record the change as data for a system that makes it: ```csharp public class MarkTargets : EcsSystem { [ForEach, With] static void Mark(Entity hunter, in Target target, World world) { hunter.RemoveTarget(); // through the parameter: this system runs alone if (world.TryGetEntity(target.Id, out var prey)) prey.SetDoomed(); // and its pass notices this one too } } ``` The rule sees the method's own body: a change made in a helper method it calls is not followed. Inside a parallel stage or a parallel `[ForEach]` the runtime still throws for it ([what the world synchronizes](https://ecs.xgamedev.net/en/docs/guide/threading#what-the-world-synchronizes)). ## EECS014 **Structural change on another thread.** Error. No code fix. A world's structure belongs to its owner thread. The rule reports a structural call (the members EECS013 lists) in a lambda or anonymous method handed to `Task.Run`, `TaskFactory.StartNew`, `new Task`, `Parallel.*`, `ThreadPool.QueueUserWorkItem` (and its relatives), `new Thread` or `new Timer`, when the world or entity it changes can be changed by another thread at the same time: - `Parallel.*` runs the delegate on several threads at once, so any world or entity captured from outside it races (`worlds[i]`, a world per item, does not); - the hand-off sits in a loop, so the delegate runs several times over the same captured world or entity; - the code around the hand-off (the method, or the type for a field) changes the same world's structure too. ```csharp public static class Spawner { public static void Start(World world, Entity[] players) { Task.Run(() => world.CreateEntity(new Position(0, 0))); // the caller changes this world too world.CreateEntity(new Position(1, 1)); Parallel.For(0, players.Length, i => players[i].Destroy()); // entities of one world, several threads at once } } ``` A world handed to a thread that then owns it (a world per thread, a world created inside the delegate) is not reported, and neither is a hand-off the caller waits for at once (`await`, `Wait()`, `Result`, `GetAwaiter().GetResult()`): nothing runs beside it. Hand the change to the owner thread as data, through a queue its system drains ([input from other threads](https://ecs.xgamedev.net/en/docs/guide/threading#input-from-other-threads)), or give the other thread its own world: ```csharp public static class WorldThreads { // A world per thread: each thread owns its world, nothing is shared. public static Thread[] Start(World[] worlds) { var threads = new Thread[worlds.Length]; for (int i = 0; i < worlds.Length; i++) { var zone = worlds[i]; // one variable per iteration threads[i] = new Thread(() => { for (int t = 0; t < 1_000; t++) zone.Update(); }); threads[i].Start(); } return threads; } } ``` Like EECS013, the rule sees the delegate's own body, and a receiver it cannot follow (a method's result) is not reported. ## EECS015 **Indexed component written through a ref.** Error. No code fix. A [value index](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#value-indexes) follows `Set`, `CreateEntity` and `CreateEntities`; a write through a `ref` changes the key behind its back. For a component implementing `IIndexed` (or `IGroup`, whose [group](https://ecs.xgamedev.net/en/docs/guide/groups) is a key too), the rule reports: - `Get()`, `GetOrAdd()` or `TryGetRef()` on an entity; - a `ref` local bound to it, or an assignment to it (or a field of it) through a query item; - a `ref` or `Span` parameter of it in a `[ForEach]` method or an `IForEach*` job. ```csharp public record struct Zone(int Id) : IComponent, IIndexed { public int Key => Id; } public record struct Portal(int To) : IComponent; ``` ```csharp public class TakePortals : EcsSystem { [ForEach] static void Take(ref Zone zone, in Portal portal) => zone = new Zone(portal.To); // the index keeps the old zone } ``` Read it with `in`, `ReadOnlySpan`, `Read()` or the generated property, and write it with `Set` (or the generated `SetX`): ```csharp public class TakePortals : EcsSystem { [ForEach] static void Take(Entity player, in Zone zone, in Portal portal) { if (zone.Id != portal.To) player.SetZone(portal.To); // a Set: the index moves the player at once } } ``` ## EECS016 **`[Removed]` method that requires `T`.** Error. No code fix. `[Removed]` visits entities that lost `T` and still lack it. Taking `T` as a parameter, or requiring it with `[With]` or `[Changed]` on the same method, asks for entities that have `T`: no row passes both, so the method would never run. ```csharp public record struct Burning(int Ticks) : IComponent, ITrackChanges; public record struct Replica(int Health, bool Burning) : IComponent; ``` ```csharp public class ReplicateFire : EcsSystem { [ForEach, Removed] static void Out(in Burning burning, ref Replica replica) => replica.Burning = false; // the entity lacks Burning } ``` Read the entity's other components (the row keeps them), and handle "added again" or "written" in another method with `[Changed]`: ```csharp public class ReplicateFire : EcsSystem { [ForEach, Changed] static void Lit(ref Replica replica) => replica.Burning = true; [ForEach, Removed] // the other components of the row are still there static void Out(ref Replica replica) => replica.Burning = false; } ``` ## EECS017 **A component stores an `Entity` handle.** Warning. No code fix. An `Entity` holds a reference to its world, so a component or singleton with an `Entity` field is managed: its column is scanned by the garbage collector, every store pays a write barrier, rows are not copied as blocks, [saves](https://ecs.xgamedev.net/en/docs/guide/saves) cannot write it and [migration](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#entityid-rewriting) does not rewrite it. ```csharp public record struct Chase(Entity Prey) : IComponent; // a managed column ``` Store the `EntityId` (8 bytes, unmanaged; a handle converts to it implicitly) and turn it back into a handle with `world.TryGetEntity(id, out var entity)`, which also says whether the entity still lives: ```csharp public record struct Chase(EntityId Prey) : IComponent; public class ChaseSystem : EcsSystem { [ForEach] static void Follow(ref Position p, in Chase chase, World world) { if (world.TryGetEntity(chase.Prey, out var prey)) p = prey.Position; // gone: the id finds nothing } } ``` ## EECS018 **A system's schedule is not a constant.** Warning. No code fix. `UpdateInterval` and `UpdatePhase` are read every update, so a value that changes makes the system skip or repeat runs. ```csharp public class SaveSystem : EcsSystem { public override int UpdateInterval => World.EntityCount > 1000 ? 4 : 1; } ``` Return a constant. To stop and resume a system, set `Enabled`: ```csharp public class SaveSystem : EcsSystem { public override int UpdateInterval => 60; // every 60th update public override int UpdatePhase => 30; // half a cycle after the others with the same interval } ``` ## EECS019 **Systems ordered in a cycle.** Error. No code fix. `[UpdateBefore]` and `[UpdateAfter]` say which of two systems runs first; a cycle cannot hold, and `AddSystem` throws when the system that closes it is added. The analyzer reports the cycles it sees between the systems of the compilation. ```csharp [UpdateAfter] public class A : EcsSystem { } [UpdateAfter] public class B : EcsSystem { } // A after B after A ``` Remove one of the orderings: ```csharp public class Movement : EcsSystem { } [UpdateAfter] public class Collision : EcsSystem { } [UpdateAfter] public class Damage : EcsSystem { } ``` ## EECS020 **A system ordered against another group.** Warning. No code fix. Orderings apply within one group: `World.Update()` and `World.Update()` run their groups separately, in the order the caller calls them, so an ordering against a system of another group never applies. ```csharp public struct Late : ISystemGroup; [UpdateInGroup] public class Sweep : EcsSystem { } [UpdateAfter] public class Movement : EcsSystem { } // Movement runs in the default group ``` Order systems of one group, or move the system into the other's group: ```csharp public struct Late : ISystemGroup; [UpdateInGroup] public class Sweep : EcsSystem { } [UpdateInGroup, UpdateAfter] public class Recycle : EcsSystem { } ``` ## EECS021 **A `[ForEach]` entry point has the signature of another method.** Error. No code fix. Outside a system, the generator writes an overload of each `[ForEach]` method that takes the `World` (and the change tick, for `[Changed]` / `[Removed]`) followed by the method's other values. If the type already has a method with that signature, or another `[ForEach]` overload's entry point has it, the two collide. ```csharp public static class Healing { [ForEach] static void Heal(ref Health hp) => hp.Value++; public static void Heal(World world) { } // the entry point Heal(World) exists already } ``` Rename one of them: ```csharp public static class Healing { [ForEach] static void Heal(ref Health hp) => hp.Value++; // Healing.Heal(world) public static void HealAll(World world) => Healing.Heal(world); // the generated entry point } ``` ## EECS022 **A type out of reach of the generated code.** Error. Code fix: makes the type internal, with every private or protected type that contains it, in each part of a partial type that states an accessibility. The generator writes the jobs of `[ForEach]` methods outside the user's type and calls the methods through `UnsafeAccessor`, so private methods and private systems are fine. The types of the parameters (and return), and the type of a `[ForEach]` method outside a system, must be internal or public, as must every type containing them; a `file` type is out of reach of any other file. ```csharp public class HealSystem : EcsSystem { private struct Regen : IComponent { public int Amount; } // the generated job cannot name it [ForEach] static void Heal(ref Health hp, in Regen r) => hp.Value += r.Amount; } ``` ```csharp public class HealSystem : EcsSystem { internal struct Regen : IComponent { public int Amount; } [ForEach] static void Heal(ref Health hp, in Regen r) => hp.Value += r.Amount; } ``` ## EECS023 **A filter on a struct that is no system group.** Error. Code fix: removes the filter. `[With]`, `[Without]` and `[WithAny]` on an `ISystemGroup` struct join every `[ForEach]` method of the group's systems. On any other struct, such as a component, they do nothing. ```csharp [Without] public struct Armor : IComponent { public int Value; } // filters nothing ``` Put the filter on the methods, or on their group: ```csharp public struct Armor : IComponent, IClamped { public int Value { get; set; } } [Without] public struct Alive : ISystemGroup; // every [ForEach] of the group skips Dead entities ``` ## EECS024 **`[ForEach]` on a local function.** Error. No code fix. The generator writes a job for each `[ForEach]` method and calls it from outside its type; a local function has no name outside its method. ```csharp public static class Report { public static int Alive(World world) { int alive = 0; [ForEach, With] static void Count(ref int alive) => alive++; // nothing can call it return alive; } } ``` Make it a method of a system, or a static method of a type (its entry point takes the world): ```csharp public static class Report { [ForEach, With] static void Count(ref int alive) => alive++; public static int Alive(World world) { int alive = 0; Report.Count(world, ref alive); // the generated entry point return alive; } } ``` ## EECS025 **A write access that only reads.** Warning. Code fix: `in` for a component or singleton, `ReadOnlySpan` for a span, `Read()` for `Get()`, `.X` for `WriteX()`. A `ref` parameter (a `Span` in a batch method) puts its type in the system's write set: no [parallel stage](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems) runs the system beside one that reads the type. On a [tracked component](https://ecs.xgamedev.net/en/docs/guide/change-tracking) it also stamps every row the method visits, so `[Changed]` systems visit rows nobody changed. `entity.Get()` and the generated `entity.WriteX()` stamp the row the same way. The rule looks at every use: an assignment, `++`, a `ref` or `out` argument, a method that is not `readonly`, a `ref` local or a `this ref` extension (`DynamicBuffer.Add`) is a write, and keeps the access. ```csharp public record struct Armor(int Value) : IComponent, ITrackChanges; ``` ```csharp public class ArmorBonus : EcsSystem { [ForEach] static void Apply(ref Armor armor, ref Health health) => health = new Health(health.Value + armor.Value); // armor is only read } ``` Read it by `in`: ```csharp public class ArmorBonus : EcsSystem { [ForEach] static void Apply(in Armor armor, ref Health health) => health = new Health(health.Value + armor.Value); } ``` ## EECS026 **A `[ForEach]` parameter the method does not use.** Warning. Code fix: a component becomes a `[With]` filter (or goes, when a `[With]` or `[Changed]` already requires it); an `Entity`, `World`, `EntitySpan`, singleton or `Maybe` goes. Each parameter costs something on every row or every pass: a component's column is loaded and advanced, a singleton is resolved and scheduled as an access, an `Entity` builds a handle for every row and, like the `World`, makes the system [run alone](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems). A component the method only requires is a filter. An unused `ref` of a tracked component is reported without a fix: it stamps every row it visits, and `[With]` would not. A method with an empty body is left alone while it is being written. ```csharp public record struct Survivors(int Count) : ISingletonComponent; ``` ```csharp public class CountSurvivors : EcsSystem { [ForEach, Without] static void Count(in Health health, ref Survivors survivors) => survivors = new Survivors(survivors.Count + 1); } ``` Require the component with a filter: ```csharp public class CountSurvivors : EcsSystem { [ForEach, With, Without] static void Count(ref Survivors survivors) => survivors = new Survivors(survivors.Count + 1); } ``` ## EECS027 **A lookup per row that a parameter makes once.** Warning. No code fix. A `[ForEach]` method's parameters are resolved once per table or per pass: a component is a column the loop walks, a singleton a `ref` taken before the loop. The same data looked up through the visited `Entity` (`entity.Velocity`, `entity.Has()`, `entity.TryGet(...)`) or through the `World` (`World.Clock`) repeats the search on every row: the entity's record, its table, the column. The rule reports only lookups that run on every row (not in a branch, a loop or after an early `return`), of components the method does not add or remove itself, and not of indexed components. ```csharp public class Drift : EcsSystem { [ForEach] static void Move(Entity entity, ref Position position) => position = new Position(position.X + entity.Velocity.X, position.Y + entity.Velocity.Y); } ``` Take the component as a parameter (`in`, `ref`, or `Maybe` when some entities lack it; a presence test is a `Maybe` or a `[With]` / `[Without]` split), and a singleton as a parameter too: ```csharp public class Drift : EcsSystem { [ForEach] static void Move(ref Position position, in Velocity velocity) => position = new Position(position.X + velocity.X, position.Y + velocity.Y); } ``` ## EECS028 **An allocation in code that runs every update.** Warning. No code fix. A `[ForEach]` method runs for every entity it visits and `OnUpdate` once per update, so what they allocate is garbage of every tick, and the collections it causes pause the world. The rule names each allocating expression: an object or array, a lambda that captures, a method group of an instance, LINQ, a string built at run time (`$"..."`, `+`, `string.Format`, `ToString()`), boxing, and `foreach` over an interface. Left out: code inside a `throw`, calls the compiler removes (`[Conditional]`, such as `Debug.Assert`), console output (the write costs more than its string), and the `OnUpdate` of a system that overrides `UpdateInterval` (its author chose that cadence). ```csharp public class Steer : EcsSystem { [ForEach] static void Aim(in Position position, ref Velocity velocity) { var path = new List { position }; // a list for every entity, every update velocity = new Velocity(-path[0].X, -path[0].Y); } } ``` Keep values in structs, spans and `stackalloc`; keep a reusable collection in a component or a singleton taken by `ref`; pass numbers, not strings: ```csharp public class Steer : EcsSystem { [ForEach] static void Aim(in Position position, ref Velocity velocity) { Span path = stackalloc Position[1]; path[0] = position; velocity = new Velocity(-path[0].X, -path[0].Y); } } ``` ## EECS029 **An instance `[ForEach]` method that uses no instance member.** Warning. Code fix: makes it `static`. An instance method could reach the `World` through its system, so the generator treats it as one that may change structure: its system runs alone in a parallel stage, and its rows are walked with the checks a structural change needs. A static method that takes no `Entity` or `World` is proven not to change structure ([EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013)). ```csharp public class MoveSystem : EcsSystem { [ForEach] void Move(ref Position position, in Velocity velocity) => position = new Position(position.X + velocity.X, position.Y + velocity.Y); } ``` Make it static: ```csharp public class MoveSystem : EcsSystem { [ForEach] static void Move(ref Position position, in Velocity velocity) => position = new Position(position.X + velocity.X, position.Y + velocity.Y); } ``` ## EECS030 **A structural change entity by entity over a query.** Warning. Code fix: the bulk call. A structural change through each entity of a query moves (or flips) one row per call, through the structural gate each time. `SetAll`, `RemoveAll`, `DisableAll`, `EnableAll` and `DestroyEntities` change every matching row of a table together, whole words of rows at once ([bulk changes](https://ecs.xgamedev.net/en/docs/guide/bulk)). The rule reports a `foreach` over `world.Query<...>()` whose body is one such call on the item's entity with the same value for every row. A `Set` of a component the query already requires writes a value instead of moving a row, and is left alone. ```csharp foreach (var item in world.Query(QueryFilter.Create().With())) item.Entity.Destroy(); ``` One call: ```csharp world.DestroyEntities(QueryFilter.Create().With()); ``` ## EECS031 **Entities created one by one in a counted loop.** Warning. Code fix: the bulk call, or a reservation before the loop. Created one by one, a table and the entity storage grow by doubling, and in a world that has never held them the discarded arrays can set off a full garbage collection ([D28](https://ecs.xgamedev.net/en/docs/decisions#d28-reservations-grow-to-what-they-need-entity-storage-on-the-pinned-heap)). `CreateEntities` and `Instantiate(prefab, span)` create them in one pass; `EnsureCapacity` reserves room when each entity gets values of its own. The rule leaves out loops of a constant count under 4,096, or over an array created with one (no array reaches the large object heap), loops after a reservation, loops that create only under a branch or in an inner loop, and loops in a system (a running world reuses its rows). ```csharp var wave = new Entity[50_000]; for (int i = 0; i < wave.Length; i++) wave[i] = world.CreateEntity(new Position(0, 0), new Health(100)); ``` One call when the values are the same; a reservation when they are not: ```csharp var spawned = new Entity[50_000]; world.CreateEntities(spawned, new Position(0, 0), new Health(100)); world.EnsureCapacity(spawned.Length); for (int i = 0; i < spawned.Length; i++) world.CreateEntity(new Position(i, 0), new Health(100)); ``` ## EECS032 **Query work the world does in one call.** Warning. Code fix: `Any`, or `Count` for a loop that only counts. `Count` sums the row counts of the matching tables and `Any` stops at the first table with a row; neither visits a row. A filter skips whole tables and words of rows that a test in the loop visits one by one. The rule reports `Count<...>()` compared with 0 or 1 as a presence test, a `foreach` over a query that only counts, and a loop whose first statement skips rows by a component test of the item's entity (no fix: the filter goes where the query is made). ```csharp bool anyDead = world.Count() > 0; ``` ```csharp bool someoneDied = world.Any(); foreach (var item in world.Query(QueryFilter.Create().With())) { } // the filter, not a test in the loop ``` ## EECS033 **A generic call with a generated member of the same meaning.** Info. Code fix: the generated member. The generator writes [named members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members) for every component, singleton, buffer element and query shape, each calling the generic API: the same call at the same cost, which is why this rule is a suggestion and not a warning. The rule offers the member only where it is generated in that compilation and does the same thing, including the kind of reference it returns: `Get()` of a tracked component becomes `WriteX()` (its `entity.X` is read-only), and a buffer's member is offered only while other code still names `DynamicBuffer` (the generator writes buffer members for the elements code names that way). | Generic | Generated | | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `entity.Get()`, `entity.Read()` | `entity.Health` (or `WriteHealth()` for a tracked component) | | `entity.Has()`, `entity.Has()` | `entity.HasHealth`, `entity.IsDead` | | `entity.TryGet(out h)`, `entity.GetOrAdd()` | `entity.TryGetHealth(out h)`, `entity.GetOrAddHealth()` | | `entity.Set(new Health(100))`, `entity.Set(new Dead())` | `entity.SetHealth(100)`, `entity.SetDead()` | | `entity.Remove()`, `Disable()`, `Enable()`, `IsDisabled()` | `entity.RemoveHealth()`, `DisableHealth()`, `EnableHealth()`, `IsHealthDisabled` | | `world.GetSingleton()`, `HasSingleton`, `GetOrAddSingleton`, `RemoveSingleton` | `world.Clock`, `HasClock`, `GetOrAddClock()`, `RemoveClock()` | | `world.Index()`, `world.Relations()` | `world.ZoneIndex`, `world.FriendIndex` | | `item.Component1` | `item.Health` | ```csharp int hpGeneric = player.Get().Value; ``` ```csharp int hp = player.Health.Value; ``` ## EECS034 **A system runs a world update.** Error. No code fix. `World.Update()` and `World.Update()` run systems. Called from a system, `Update()` runs the system again inside its own run until the stack overflows, and a group's update runs other systems in the middle of a stage, under its change tick. A stable `[ForEach]` method that calls it is [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013). ```csharp public class CatchUp : EcsSystem { protected override void OnUpdate() => World.Update(); } ``` The code that hosts the world runs its updates and groups, in the order they belong: ```csharp while (running) world.Update(); ``` ## Related - [Common mistakes](https://ecs.xgamedev.net/en/docs/guide/common-mistakes): The mistakes these rules catch, and the ones no rule can. - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): What a `[ForEach]` method may take and how it is scheduled. - [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles): The rules behind the analyzer. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): Parallel stages, parallel methods and the owner thread. --- # Common mistakes > Twenty-four mistakes people make with EasyEcs in C#, each with the code you might write, why it is wrong and the fix, plus the analyzer rule behind it. URL: https://ecs.xgamedev.net/en/docs/guide/common-mistakes Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/common-mistakes.md Most of what goes wrong with EasyEcs comes from habits of object-oriented code or of other ECS libraries. The analyzer stops about half of these mistakes at compile time; the rest compile, run and quietly do the wrong thing. Each entry below is the code you might write, why it is wrong, and what to write instead. ## Data ### Changing a copy of a component ```csharp var hp = hero.Health; // a copy of the row hp.Value -= 10; // the table still holds the old value ``` The generated property returns a `ref` (as `Get()` does), and `var` copies what it points at. Keep the `ref`, or write through the property directly: ```csharp ref var health = ref hero.Health; health.Value -= 10; hero.Health.Value -= 10; // the same, inline ``` No rule catches it. More in [copies and refs](https://ecs.xgamedev.net/en/docs/guide/refs-and-await#copies-and-refs). ### Storing an `Entity` in a component ```csharp public record struct Follow(Entity Leader) : IComponent; ``` An `Entity` holds a reference to its world: the column becomes managed (scanned by the GC, not copied as blocks), a save cannot write it and a migration does not rewrite it. Store the `EntityId` and look it up when you need it: ```csharp public record struct Follow(EntityId Leader) : IComponent; ``` Caught by [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) (warning). More in [ids, versions and recycling](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#entityid). ### Storing an index instead of an id ```csharp public record struct OwnerSlot(int Index) : IComponent; ``` ```csharp var owned = world.CreateEntity(new OwnerSlot(hero.Id.Index)); // names whichever entity reuses that index ``` Ids are recycled: once the owner is destroyed, the index goes to the next entity created. An `EntityId` carries the version too, so `TryGetEntity` finds nothing once the owner is gone: ```csharp public record struct Owner(EntityId Id) : IComponent; ``` ```csharp var item = world.CreateEntity(new Owner(hero.Id)); if (world.TryGetEntity(item.Owner.Id, out var owner)) { /* still alive */ } ``` No rule catches it. More in [ids, versions and recycling](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#entityid). ### A flag where a tag would do ```csharp public record struct Mobility(bool Rooted) : IComponent; public class MoveRooted : EcsSystem { [ForEach] static void Move(ref Position p, in Velocity v, in Mobility m) { if (m.Rooted) return; // every row is visited and tested p.X += v.X; p.Y += v.Y; } } ``` A flag makes every system that cares visit every row and branch on it. A tag is a component with no fields: queries skip the whole table, and adding or removing it is the state change: ```csharp public struct Rooted : IComponent; public class MoveFree : EcsSystem { [ForEach, Without] // rooted entities are never visited static void Move(ref Position p, in Velocity v) { p.X += v.X; p.Y += v.Y; } } ``` For a state that flips every tick, a field is cheaper than a table move: see [ECS principles, rule 5](https://ecs.xgamedev.net/en/docs/ecs-principles#5-choose-the-cheapest-representation-for-frequent-changes). ### Removing a component to pause it ```csharp public record struct Cooldown(int Ticks) : IComponent; ``` ```csharp var caster = world.CreateEntity(new Cooldown(30)); var kept = caster.Cooldown; // stash the value somewhere caster.RemoveCooldown(); // stunned caster.Set(kept); // and put it back later ``` The value has to live somewhere in the meantime, and every reader of the stash is code you maintain. `DisableCooldown()` (`Disable()`) hides the component from queries, `Has` and `Get`, keeps its value in the row, and `EnableCooldown()` brings it back: ```csharp caster.DisableCooldown(); // stunned: the cooldown is paused caster.EnableCooldown(); // the stun ends: the same value ``` No rule catches it. More in [disable a component](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable#disable-a-component). ### A public `Key => this` on a record struct key ```csharp public readonly record struct Market(long Id) : IActor { public Market Key => this; // a public property: part of the record's ToString() } ``` A record struct prints its public properties in `ToString()`. `Key` returns the record itself, which prints its `Key`, which prints its `Key`: the first log line or debugger view of the value overflows the stack. Implement `Key` explicitly, so it belongs to the interface only: ```csharp public readonly record struct Market(long Id) : IActor { Market IIndexed.Key => this; } ``` No rule catches it. The [Actors sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/Actors) shows the whole pattern. ## Systems ### State in a system ```csharp public class WaveSystem : EcsSystem { private int _wave; protected override void OnUpdate() => _wave++; } ``` Nothing else can read, save or snapshot that field, and it is lost when the system is removed. Per-world state is a singleton: ```csharp public record struct Wave(int Number) : ISingletonComponent; public class WaveSystem : EcsSystem { protected override void OnUpdate() => World.GetOrAddWave().Number++; } ``` Caught by [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007). More in [ECS principles, rule 2](https://ecs.xgamedev.net/en/docs/ecs-principles#2-systems-are-stateless). ### A system that calls another ```csharp public class LootSystem : EcsSystem { } public class KillRewards : EcsSystem { protected override void OnUpdate() => World.GetSystem(); } ``` Systems that call each other cannot be removed, reordered or tested alone. One writes data (a tag, a component, a singleton), and the other reads it, ordered after it: ```csharp public struct Looted : IComponent; public class LootSystem : EcsSystem { [ForEach, With, Without] static void Drop(Entity corpse) => corpse.SetLooted(); } [UpdateAfter] public class KillRewards : EcsSystem { [ForEach, With] static void Reward(in Health hp) { } } ``` Caught by [EECS008](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs008). More in [ECS principles, rule 3](https://ecs.xgamedev.net/en/docs/ecs-principles#3-systems-never-reference-systems). ### A `ref` parameter that only reads ```csharp public record struct Speed(float Value) : IComponent; ``` ```csharp public class Throttle : EcsSystem { [ForEach] static void Apply(ref Velocity v, ref Speed max) // max is only read { v = new Velocity(Math.Min(v.X, max.Value), Math.Min(v.Y, max.Value)); } } ``` A `ref` parameter declares a write. With `ParallelSystems`, a system that writes `Speed` cannot share a stage with any other system that touches it, and if `Speed` were tracked, every row would count as changed. Read with `in`: ```csharp public class Throttle : EcsSystem { [ForEach] static void Apply(ref Velocity v, in Speed max) { v = new Velocity(Math.Min(v.X, max.Value), Math.Min(v.Y, max.Value)); } } ``` Caught by [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) (warning, with a code fix). More in [parallel systems](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems). ### `[Changed]` on a component that is not tracked ```csharp public record struct Gold(int Amount) : IComponent; public record struct Hud(int Gold) : IComponent; public class ShowGold : EcsSystem { [ForEach, Changed] static void Show(in Gold gold, ref Hud hud) => hud = new Hud(gold.Amount); } ``` Change ticks cost a column, so only components that ask for them have them. Mark the component `ITrackChanges`: ```csharp public record struct Gold(int Amount) : IComponent, ITrackChanges; public record struct Hud(int Gold) : IComponent; public class ShowGold : EcsSystem { [ForEach, Changed] static void Show(in Gold gold, ref Hud hud) => hud = new Hud(gold.Amount); } ``` Caught by the C# compiler (the attribute requires `ITrackChanges`: CS0315). More in [mark the component](https://ecs.xgamedev.net/en/docs/guide/change-tracking#mark-the-component). ### Reading a tracked component through a `ref` ```csharp int before = player.Get().Amount; // Get() is a write: the row counts as changed ``` `Get()` stamps the row, so every `[Changed]` system visits it next update. Read with the generated property (it is `ref readonly` for a tracked component), `Read()` in generic code, or an `in` parameter: ```csharp int amount = player.Gold.Amount; // ref readonly: no stamp ``` Caught by [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) (warning, with a code fix). More in [what counts as a write](https://ecs.xgamedev.net/en/docs/guide/change-tracking#what-counts-as-a-write). ### `[Removed]` that takes `T` ```csharp public record struct Burning(int Ticks) : IComponent, ITrackChanges; public record struct Glow(bool On) : IComponent; ``` ```csharp public class Extinguish : EcsSystem { [ForEach, Removed] static void Out(in Burning burning, ref Glow glow) => glow = new Glow(false); } ``` The entities `[Removed]` visits no longer have `Burning`, so the method would never run. Read the row's other components: ```csharp public class Extinguish : EcsSystem { [ForEach, Removed] static void Out(ref Glow glow) => glow = new Glow(false); } ``` Caught by [EECS016](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs016). More in [removal detection](https://ecs.xgamedev.net/en/docs/guide/change-tracking#removal-detection). ### One hand-written group per actor type ```csharp public struct In : IComponent; // the tag of one actor type public readonly record struct Shop(long Id) : IComponent; public readonly record struct Guild(long Id) : IComponent; ``` ```csharp [With>] public struct ShopGroup : ISystemGroup; // one more struct for every actor type [With>] public struct GuildGroup : ISystemGroup; ``` Every new kind of actor needs its group written again, and a generic interface cannot carry the filter as an attribute: C# refuses a type parameter there (`[With>]` is CS8968). The interfaces `IGroupWith` and `IGroupWithout` can name it, so one generic interface makes each actor type its own key component, group and filter: ```csharp public interface IActor : IComponent, IIndexed, ISystemGroup, IGroupWith> where TSelf : struct, IActor, IEquatable; public readonly record struct Shop(long Id) : IActor { Shop IIndexed.Key => this; } public readonly record struct Guild(long Id) : IActor { Guild IIndexed.Key => this; } ``` No rule catches it. More in [group filters](https://ecs.xgamedev.net/en/docs/guide/systems#group-filters). ## Structure ### Keeping a `ref` across a structural change ```csharp ref var life = ref hero.Health; hero.SetStunned(); // the row moves to another table life.Value -= 10; // writes the old copy ``` Adding or removing a component moves the entity's row, and a `ref` taken before points at the old place. Get it again after the change: ```csharp hero.SetStunned(); hero.Health.Value -= 10; ``` No rule catches it. More in [refs across a change](https://ecs.xgamedev.net/en/docs/guide/structural-changes#refs-across-a-change). ### Keeping a `ref` across an `await` ```csharp ref var stamina = ref hero.Health; await Task.Delay(100); stamina.Value -= 10; ``` The compiler refuses it (CS9217), and with reason: anything may happen to the row while the method waits. Keep the `Entity` and get the component again after the `await`, on the owner thread: ```csharp await Task.Delay(100); if (hero.HasHealth) hero.Health.Value -= 10; ``` Caught by the C# compiler. More in [across `await`](https://ecs.xgamedev.net/en/docs/guide/refs-and-await#across-await). ### Writing an indexed key through a `ref` ```csharp public record struct Zone(int Id) : IComponent, IIndexed { public int Key => Id; } ``` ```csharp public static class Portals { public static void Enter(Entity player) => player.Get() = new Zone(2); } ``` The index follows `Set`; a write through a `ref` changes the key behind its back, and lookups keep finding the player in the old zone. Write it with `Set` or the generated `SetX`: ```csharp public static class Portals { public static void Enter(Entity player) => player.SetZone(2); } ``` Caught by [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015). More in [value indexes](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations#value-indexes). ### Copying a `DynamicBuffer` ```csharp public record struct Loot(int Item); ``` ```csharp public static class Inventory { public static void Give(Entity player, Loot loot) { var bag = player.Read>(); // a copy that shares the list bag.Add(loot); // the write is never stamped } } ``` A buffer refers to its list: a copy writes to the same list without marking the entity changed, and storing it gives two entities one list. Reach it through the entity: ```csharp public static class Inventory { public static void Give(Entity player, Loot loot) { ref var bag = ref player.Get>(); bag.Add(loot); } } ``` Caught by [EECS012](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs012). More in [dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers). ### Destroying a parent and expecting the children to stay ```csharp var ship = world.CreateEntity(new Position(0, 0)); var turret = world.CreateEntity(new Position(1, 0), new ChildOf(ship)); ship.Destroy(); // the turret is destroyed with it ``` `ChildOf` starts with `TargetPolicy.Destroy`: destroying a parent destroys its subtree. Choose what happens to the children once, for the world: ```csharp world.Index().WhenTargetDestroyed(TargetPolicy.Remove); // orphans become roots ``` No rule catches it. More in [cascade policy](https://ecs.xgamedev.net/en/docs/guide/hierarchy#cascade-policy). ### A loop of structural changes ```csharp public struct Fighter : IComponent; ``` ```csharp foreach (var item in world.Query()) item.Entity.SetFrozen(); // one structural change per entity ``` Each call moves one row. `SetAll`, `RemoveAll`, `DisableAll` and `EnableAll` move a table's rows together: ```csharp int frozen = world.SetAll(new Frozen(), QueryFilter.Create().With()); ``` Caught by [EECS030](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs030) (warning, with a code fix). More in [bulk changes](https://ecs.xgamedev.net/en/docs/guide/bulk). ### Collecting a subtree with `Children` alone ```csharp var subtree = new List { hero.Id }; foreach (var child in world.Children(hero)) subtree.Add(child.Id); // grandchildren are left out ``` `Children` lists one level. A save or a move of that group leaves the grandchildren behind, and they die with the original. `Descendants` walks every level, depth first: ```csharp var group = new List { hero.Id }; foreach (var part in world.Descendants(hero)) group.Add(part.Id); // children, grandchildren, ... ``` No rule catches it. More in [moving a hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy#moving). ### Restoring a record that is then saved again ```csharp public record struct Bank(long Gold) : IComponent, ITrackChanges; // persistent: saved when it changes public record struct Connection(int Socket) : IComponent; // runtime only ``` ```csharp static Entity Activate(World world, ReadOnlySpan record) { var actor = world.CreateEntity(new Connection(9), new Bank(0)); // a new actor's default world.LoadEntitiesInto(record, [actor]); // a write: the saver sends Bank back return actor; } ``` A load counts as a write, so the system that saves or replicates `[Changed]` rows writes the record straight back to where it came from, on every activation. Load it with `markWritten: false`: the stored `Bank` replaces the default and counts as never written, so the saver skips the actor until code changes it: ```csharp static Entity Restore(World world, ReadOnlySpan record) { var actor = world.CreateEntity(new Connection(9), new Bank(0)); // the same default as a new actor world.LoadEntitiesInto(record, [actor], markWritten: false); // Bank as stored, not a change return actor; } ``` No rule catches it. More in [records](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records). ## Threads ### Changing a world from another thread ```csharp public static class Network { public static void OnJoin(World world) { Task.Run(() => world.CreateEntity(new Position(0, 0))); world.CreateEntity(new Position(1, 1)); } } ``` A world's structure belongs to its owner thread, and the world adds no lock to share it. Put the input in a queue and let a system on the owner thread turn it into entities, or give each thread its own world. Caught by [EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs014). More in [input from other threads](https://ecs.xgamedev.net/en/docs/guide/threading#input-from-other-threads). ### A structural change in a parallel method ```csharp public class Reap : EcsSystem { [ForEach(Parallel = true)] static void Kill(Entity e, in Health hp) { if (hp.Value <= 0) e.SetDead(); } } ``` Chunks of rows run on several threads at once, so none may move rows. Keep the parallel part to values, and let a sequential method change structure: ```csharp public class Reap : EcsSystem { [ForEach, Without] static void Kill(Entity e, in Health hp) { if (hp.Value <= 0) e.SetDead(); } } ``` Caught by [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010). More in [parallel `[ForEach]` methods](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-foreach-methods). ### `entity.Run` in a parallel method ```csharp public struct Mend : IForEachEntity { public static int Writes => 1; public void Execute(Entity target, ref Health hp) => hp.Value += 1; } ``` ```csharp public class HealAll : EcsSystem { [ForEach(Parallel = true), With] static void Heal(Entity e) { var mend = new Mend(); e.Run(ref mend); // bookkeeping of the owner's pass, and the job may change structure } } ``` `entity.Run` is for a request or a message to one entity, on the owner thread. It does the bookkeeping of the owner's pass and its job may change structure, so a parallel method cannot call it. A `[ForEach]` method already gets the refs a job would get; write through them: ```csharp public class HealAll : EcsSystem { [ForEach(Parallel = true)] static void Heal(ref Health hp) => hp.Value += 1; } ``` Caught by [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010). More in [one entity: `entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity). ## Related - [Analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer): Every rule, EECS002 to EECS034. - [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles): The rules these mistakes break. - [ref and await](https://ecs.xgamedev.net/en/docs/guide/refs-and-await): When a `ref` expires. - [FAQ](https://ecs.xgamedev.net/en/docs/faq): Short answers to common questions. --- # Troubleshooting > What each EasyEcs exception message means and how to fix it, and why a system does not run, a generated member is missing or a save drops data. URL: https://ecs.xgamedev.net/en/docs/guide/troubleshooting Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/guide/troubleshooting.md Most mistakes never reach run time: the [analyzer](https://ecs.xgamedev.net/en/docs/guide/analyzer) rejects them while you type. This page is for the rest: the exceptions EasyEcs throws, quoted as they appear, and the problems that throw nothing. Search the page for the first words of your message. | Message starts with | Section | | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | `A structural change started while another one was running` | [Two structural changes at once](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#structural-change-running) | | `A structural change was made while the world's structure is frozen` | [A change while the structure is frozen](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#structure-frozen) | | `Entity is not alive` | [A stale or default handle](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#entity-not-alive) | | `Entity has no X component` | [A missing component](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#no-component) | | `Singleton X was not added to this world` | [A missing singleton](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#singleton-not-added) | | `The entity has no X (check HasValue)` | [An empty `Maybe`](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#maybe-empty) | | `X already belongs to a world` | [A system added twice](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#system-in-a-world) | | `[UpdateBefore] / [UpdateAfter] form a cycle` | [An ordering cycle](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#ordering-cycle) | | `The ChildOf links form a cycle` | [A `ChildOf` cycle in `Descendants`](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#childof-cycle) | | `X cannot be disabled: remove it instead` | [Disabling a cleanup component or `ChildOf`](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#cannot-disable) | | `Snapshots cannot be captured or restored while a query iterates`, `Types cannot be removed during a pass` | [Calls that wait for the end of a pass](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#during-a-pass) | | `Not an EasyEcs save`, `The size of X changed`, `The fields of X changed`, `X was saved as`, `Types of this process share the save id`, `A damaged save` | [A save that does not load](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#save-refused) | The problems that throw nothing: [a system that never runs](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#system-does-not-run), [systems that do not run in parallel](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#not-parallel), [a missing generated member](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#member-missing), [`entity.Run` returning `false`](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#run-false), [a lost write through a `ref`](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#ref-lost), [a component dropped by a load](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#save-dropped-data), [an interface another generator adds](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#other-generators) and [a stack overflow in an actor key's `ToString`](https://ecs.xgamedev.net/en/docs/guide/troubleshooting#key-tostring-overflow). ## Why does a structural change throw "started while another one was running"? ```text InvalidOperationException: A structural change started while another one was running on this world: structural changes are made by the world's owner thread, one at a time ``` Two structural changes (create, destroy, `Set`, `Remove`, a singleton or system added) overlapped on one world. Either a second thread changed the world while its owner did, or code running inside a change (a callback of your own around EasyEcs calls) started another. EasyEcs checks a plain flag, so it catches many such races, not all of them. **Fix:** change a world from one thread at a time. Other threads hand their changes over as data, through a queue a system drains on the owner's thread ([input from other threads](https://ecs.xgamedev.net/en/docs/guide/threading#input-from-other-threads), [hosting](https://ecs.xgamedev.net/en/docs/guide/hosting#requests)), or each thread gets its own world. ## Why does a structural change throw "while the world's structure is frozen"? ```text InvalidOperationException: A structural change was made while the world's structure is frozen (systems or a parallel [ForEach] running on several threads, or a batch job holding spans into the tables) ``` The change was made while other code held the tables still: inside a parallel stage of systems (`ParallelSystems`), a `[ForEach(Parallel = true)]` method, a batch method or `ForEachBatch` job (spans point into the columns), or a job marked `INoStructuralChanges`. The analyzer reports the changes it sees there ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010), [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013)); this one came through a helper or a handle it could not follow. **Fix:** record the change as data (a tag, a component, a request entity) and make it in a system or `[ForEach]` method that runs alone: one that takes `Entity` or `World`, or an `OnUpdate`. ## Why is my entity "not alive"? ```text InvalidOperationException: Entity is not alive (destroyed, or a default handle) ``` `Get`, `GetOrAdd`, `Set`, `Remove` or `Destroy` was called on a handle whose entity was destroyed (its id may already belong to another entity: the version tells them apart), or on `default(Entity)`. Questions answer false instead of throwing: `IsAlive`, `Has()` and `TryGet()`. **Fix:** check `entity.IsAlive` where an entity may have died since you took its handle, and keep `EntityId`s in components, resolving them with `world.TryGetEntity(id, out var entity)` ([entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components)). ## Why does `Get()` say the entity has no component? ```text InvalidOperationException: Entity has no Mana component ``` `Get()` (and the generated `entity.Mana`) needs the component; a component that was removed or [disabled](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) counts as absent. **Fix:** `TryGet(out var value)` or the generated `TryGetMana(out …)` where it is optional, `GetOrAdd()` to add a default, or in a `[ForEach]` method a [`Maybe` parameter](https://ecs.xgamedev.net/en/docs/guide/systems#maybe) or a second method split by `[With]` / `[Without]`. ## Why is a singleton "not added to this world"? ```text InvalidOperationException: Singleton Clock was not added to this world: set it before the systems that read it run (world.SetClock(...) or world.AddSingleton()), or use GetOrAddClock() where a default is meant ``` Code read a singleton nobody added: `world.GetSingleton()`, the generated `world.Clock`, `world.SingletonRef()`, or a `[ForEach]` method that takes `Clock` as a parameter. A parameter is resolved when its system runs, so the first `Update()` throws, even when no entity matches. The world does not invent the singleton, because its default is rarely right: a clock with no step would leave every entity standing still, with no error to point at the missing setup ([singletons](https://ecs.xgamedev.net/en/docs/guide/singletons#in-systems)). **Fix:** add it where the world is built, before the first `Update()` (`world.SetClock(…)`, `world.AddSingleton()`), or use `GetOrAddSingleton()` / `GetOrAddClock()` where a default value is right. ## Why does `Maybe.Value` throw? ```text InvalidOperationException: The entity has no Mana (check HasValue) ``` The entity the method visits has no `T`. **Fix:** test `HasValue` before reading `Value` ([`Maybe`](https://ecs.xgamedev.net/en/docs/guide/systems#maybe)). ## Why does `AddSystem` say the system "already belongs to a world"? ```text InvalidOperationException: ReceiveSpawns already belongs to a world ``` A system instance lives in one world. **Fix:** create one instance per world (`world.AddSystem()` creates a new one each time). Note that the same system type can be added twice to one world, and then runs twice per update. ## Why does `AddSystem` report a cycle? ```text InvalidOperationException: [UpdateBefore] / [UpdateAfter] form a cycle among A, B ``` The orderings of the named systems cannot all hold. The analyzer reports the cycles it sees in one compilation ([EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019)); this one spans assemblies. **Fix:** remove one of the orderings. ## Why does `Descendants` throw "The ChildOf links form a cycle"? ```text InvalidOperationException: The ChildOf links form a cycle ``` `world.Descendants(root)` met an entity it had already visited: an entity is its own ancestor, because a `Set(new ChildOf(…))` made a parent the child of one of its descendants. EasyEcs does not check a re-parent (that would be a walk up the tree on every `Set`), so the walk finds the cycle when it reaches it. **Fix:** before re-parenting `child` under `parent`, walk up from `parent` through `ChildOf` and refuse when you meet `child`. Detach first (`Remove()`) when an entity moves under one of its own descendants ([re-parent and detach](https://ecs.xgamedev.net/en/docs/guide/hierarchy#reparent)). ## Why can a component not be disabled? ```text InvalidOperationException: ChildOf cannot be disabled: remove it instead ``` `Disable()` keeps a value hidden from queries. A [cleanup component](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) and `ChildOf` cannot be hidden that way: the world must keep seeing them to finish a destroy and keep a hierarchy. **Fix:** remove the component, or disable another component that systems filter on. ## Why must `Capture`, `Restore` or `RemoveTypes` wait for a pass? ```text InvalidOperationException: Snapshots cannot be captured or restored while a query iterates InvalidOperationException: Types cannot be removed during a pass ``` They rewrite or drop whole tables, which a `foreach` over a query or a running system is walking. **Fix:** call them between updates, outside any query loop ([snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots), [unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#remove-types)). `Restore` also refuses a snapshot of another world (`ArgumentException`) and one taken before `RemoveTypes` dropped some of its tables. ## Why does a save not load? ```text InvalidDataException: Not an EasyEcs save (or one of another format version) InvalidDataException: The size of Stock changed (8 bytes saved, 12 now): its saves cannot be loaded (…) InvalidDataException: The fields of Stock changed since the save: its saves cannot be loaded (…) InvalidDataException: Stock was saved as raw rows and is written by its Nino formatter now: its saves cannot be loaded InvalidDataException: Types of this process share the save id … (…): unload or rename one of them (…) InvalidDataException: A damaged save: … ``` A load checks every component against the code that reads it, and a refused load leaves the world as it was. - **Not an EasyEcs save:** the bytes are something else, cut short, or written by another save format version (a save of EasyEcs 4.3 or earlier). - **Size or fields changed:** a raw unmanaged component's fields were added, removed, renamed or retyped since the save, or a `[NinoType]` component changed in a way its Nino format does not allow. Make a component whose shape will change a `[NinoType]` with the `VersionTolerant` or `Keyed` format, or keep the old type and convert it in a system ([when the code changed](https://ecs.xgamedev.net/en/docs/guide/saves#versioning)). - **Raw rows and Nino:** `[NinoType]` was added to or removed from an unmanaged component since the save. - **A shared save id:** two types of the process have one id: the same namespace-qualified name (two versions of a plugin loaded at once), or a `[NinoFormerName]` that is another type's name. Unload the old version first, or rename one of them. - **A damaged save:** a count or an id is out of range, or a buffer is longer than its bytes: the bytes are corrupt. ## Why does my system never run? Check, in this order: 1. **It was added** to this world: `world.Systems` lists every system. 2. **It is enabled:** `Enabled` is true, and `Error` is null. Under `SystemErrorPolicy.Disable` an exception switched it off; setting `Enabled = true` clears the error and retries. 3. **Its group is updated:** a system with `[UpdateInGroup]` runs only on `world.Update()`, never on `world.Update()`. 4. **Its interval is due:** with `UpdateInterval => N`, it runs on every N-th update of its group, first on the N-th, shifted by `UpdatePhase`. 5. **Its filters match:** count what the method needs with `world.Count(filter)`. The group's filters apply to every method of the group: `[With]`, `[Without]` and `[WithAny]` on the group struct, and `IGroupWith` / `IGroupWithout` from the group or any interface it implements (a generic actor interface carries them). A disabled component counts as absent. 6. **There was something to see:** a `[Changed]` method visits only rows written since its system last ran, and a `[Removed]` method only entities that lost `T` since then ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking#ticks)). `WorldOptions.MeasureSystems` counts every run in `system.Stats.Runs`, which tells "never ran" from "ran and did nothing". ## Why does `entity.Run` return `false`? `entity.Run(ref job, filter)` runs the job only when the entity can take it, and says `false`, without running it, when: 1. **The entity is not alive:** destroyed since you took its handle, or `default(Entity)`. `Run` does not throw for it, unlike `Get`. 2. **It lacks a component the job takes:** every type argument before `TJob` must be present (a disabled component counts as absent). Check with `entity.Has()`. 3. **It fails the filter:** a `Without` it has, a `WithAny` it misses, a `Changed(tick)` it was not written since, a group it is not in. Run once without the filter to tell this case from the others. **Fix:** treat `false` as the answer to the request (the actor is gone, the unit is dead) rather than an error, and look up the entity again by its `EntityId` when it may have been replaced ([one entity: `entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity)). ## Why do my systems not run in parallel? With `ParallelSystems`, a system shares a stage only when its access is known and does not conflict. A system runs alone when it takes an `Entity` or `World` parameter, has an instance `[ForEach]` method, overrides `OnUpdate`, or has no `[ForEach]` method. Two systems conflict when one writes what the other reads or writes, and a `ref` parameter counts as a write even when the body only reads it: use `in` ([parallel systems](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems)). An ordering (`[UpdateAfter]`) also puts the later system in a later stage. ## Why is a generated member missing? The generator writes `entity.Health`, `SetHealth(…)`, `world.Clock` and the others as C# 14 extension members. It writes nothing when: - The project compiles with a language version below C# 14 (`` set lower than the .NET 10 default). - The type is generic, or nested in a type the generated code cannot see. - The receiver already has a member of that name: a component named `Id` gets no `entity.Id` (the handle has one), and a member you wrote yourself wins. - The component is indexed (`IIndexed`): it has no `GetOrAddX()`, and `entity.X` is read-only; write it with `SetX(…)`. The generic API always works: `Get()`, `Read()`, `Set(…)`, `Has()`, `Remove()`, `GetSingleton()` ([generated members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components)). ## Why did a value I wrote through a `ref` disappear? A `ref` from `entity.Get()` or a query item is valid until the next structural change of the world, which can move rows, and never across an `await`. A write through an older `ref` lands in memory the entity no longer uses. Read again through the handle after the change ([refs and await](https://ecs.xgamedev.net/en/docs/guide/refs-and-await)). A tracked or indexed component is read-only through `entity.X` and `Read()`: writes go through `Set(…)`, or the generated `WriteX()` for a tracked one, so that the change is stamped ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking#write-as-usual)). ## Why did a component vanish after a load? A save names each type by its Nino type id (a hash of its namespace-qualified name), and a load skips the types this process does not have. A component renamed or moved to another namespace since the save loads as missing: its data is dropped without an error. Put `[NinoFormerName("Old.Namespace.Name")]` on the renamed type, and its old rows load ([when the code changed](https://ecs.xgamedev.net/en/docs/guide/saves#versioning)). ## Why does the generator not see an interface another generator adds? A component, singleton or system must declare its EasyEcs interface (`IComponent`, `ITrackChanges`, `IIndexed` and the others) in code you wrote. Source generators all run on the same input and none sees the others' output, so when another generator adds `IComponent` to a partial type, EasyEcs's generator never learns that the type is a component: it writes no members for it, and a load finds the type only once the process has used it. Write the interface on your own declaration; the other generator may still add its members to the same partial type. ## Why does my actor key crash with a stack overflow in `ToString`? A record struct that is its own key (`IIndexed`, the actor pattern) and implements `Key` as a public property, `public Shop Key => this;`, prints its public properties in `ToString()`: `Key` prints the record, which prints `Key`, until the stack overflows. A log line, a string interpolation or the debugger's view of the value is enough to trigger it. **Fix:** implement `Key` explicitly, `Shop IIndexed.Key => this;`: the index still finds it, and `ToString()` no longer sees it ([common mistakes](https://ecs.xgamedev.net/en/docs/guide/common-mistakes#public-key)). ## Related - [Common mistakes](https://ecs.xgamedev.net/en/docs/guide/common-mistakes): The mistakes, the code that makes them and the fix. - [Analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer): EECS002 to EECS034, what triggers each and how to fix it. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): The owner thread and what the world synchronizes. - [Debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics): Look inside a running world: tables, entities, system timing and errors. --- # Comparison with other ECS libraries > Which C# ECS is fastest? EasyEcs against Friflo.Engine.ECS, Arch and DefaultEcs, feature by feature: every benchmark sorted by lead, losses explained. URL: https://ecs.xgamedev.net/en/docs/comparison Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/comparison.md Which C# ECS is fastest depends on the work. EasyEcs is measured against Friflo.Engine.ECS, Arch and DefaultEcs in 37 head-to-head benchmarks: it is faster in 24, within the measurement error in 11 and slower in 2. The biggest leads are in the work a server does in bulk or now and then (saving, bulk changes, spawning, value queries, hierarchies, indexes, change detection); plain iteration over dense columns is close, because there the loop is bound by memory, not by the library. This page lists every result, sorted by lead, losses included and explained. - Head-to-head benchmarks EasyEcs is faster in: **24 / 37**, Against Friflo.Engine.ECS, Arch and DefaultEcs, beyond the measurement error - Save 10,000 entities and load them back, vs DefaultEcs: **30× faster**, EasyEcs 146 μs, DefaultEcs 4.33 ms - Add a component to 100,000 entities by query, then remove it, vs Arch: **15× faster**, EasyEcs 78.7 μs, Arch 1.21 ms - Spawn 10,000 entities beside 100,000, then destroy them, vs Friflo.Engine.ECS: **2.75× faster**, EasyEcs 138 μs, Friflo.Engine.ECS 380 μs | What is measured | EasyEcs | Next fastest | Its time vs EasyEcs | The others | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ------------------------------------- | ------------------- | ----------------------------------------------------------------------------- | | [Save 10,000 entities and load them back](https://ecs.xgamedev.net/en/docs/comparison#saves) | 146 μs | DefaultEcs 4.33 ms, 4.37 MB allocated | 30× | Friflo.Engine.ECS 143×, 6.52 MB allocated | | [Add a component to 100,000 entities by query, then remove it](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 78.7 μs | Arch 1.21 ms | 15× | DefaultEcs 103×; Friflo.Engine.ECS 154×, 4.00 MB allocated | | [Spawn 10,000 entities beside 100,000, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 138 μs | Friflo.Engine.ECS 380 μs | 2.75× | Arch 2.96×; DefaultEcs 9.7×, 313 KB allocated | | [Query 100,000 players by value: a rating range, zone sums](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 127 μs | Friflo.Engine.ECS 317 μs | 2.49× | — | | [Create 1,000 parent-child squads, destroy them in cascade](https://ecs.xgamedev.net/en/docs/comparison#hierarchy) | 452 μs | Friflo.Engine.ECS 1.06 ms | 2.35× | — | | [Count 100 inventories through an index (1 item traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 425 ns | DefaultEcs 838 ns | 1.97× | Friflo.Engine.ECS 3.2× | | [Add a status component to 5% of 100,000 entities, then remove it](https://ecs.xgamedev.net/en/docs/comparison#operations) | 517 μs | Friflo.Engine.ECS 1.00 ms | 1.94× | — | | [Find the 10 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 507 ns | Arch 966 ns | 1.91× | Friflo.Engine.ECS 2.85×; DefaultEcs 73× | | [Spawn 5,000 entities from a prefab, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#operations) | 164 μs | Friflo.Engine.ECS 276 μs | 1.68× | — | | [Create 100,000 three-component entities one by one in a fresh world, room reserved first](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.60 ms, 3.44 MB allocated | Arch 4.21 ms, 4.62 MB allocated | 1.62× | Friflo.Engine.ECS 4.7×, 4.30 MB allocated | | [Iterate one component over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#operations) | 37.7 μs | Friflo.Engine.ECS 59.9 μs | 1.59× | — | | [Put 10,000 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 478 μs | DefaultEcs 745 μs | 1.56× | Friflo.Engine.ECS 1.67×; Arch 2.63× | | [Create 100,000 three-component entities in a fresh world in one call (the others' fastest way)](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.71 ms, 4.96 MB allocated | Arch 4.21 ms, 4.62 MB allocated | 1.56× | Friflo.Engine.ECS 4.5×, 4.30 MB allocated; DefaultEcs 6.3×, 19.1 MB allocated | | [Count 100 inventories through an index (100 items traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 5.11 μs | DefaultEcs 7.87 μs | 1.54× | Friflo.Engine.ECS 1.63× | | [Iterate with a filter: the players among 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#operations) | 11.3 μs | Friflo.Engine.ECS 16.6 μs | 1.46× | — | | [Find the 1,000 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 38.5 μs | Friflo.Engine.ECS 53.7 μs | 1.40× | DefaultEcs 2.01×; Arch 2.18× | | [Iterate with the entity handle of each row](https://ecs.xgamedev.net/en/docs/comparison#operations) | 49.0 μs | Friflo.Engine.ECS 67.2 μs | 1.37× | — | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. EasyEcs is measured against the three most used .NET ECS libraries: [Friflo.Engine.ECS](https://github.com/friflo/Friflo.Engine.ECS), [Arch](https://github.com/genaray/Arch) and [DefaultEcs](https://github.com/Doraku/DefaultEcs), at the versions pinned in [`benchmarks/EasyEcs.Comparison`](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/benchmarks/EasyEcs.Comparison) (the chart labels name them). Every comparison ports the same work to each library through the path its docs recommend, and checks in setup that every library computes the same result before anything is measured. This page is the overview; the head-to-head pages ([Arch](https://ecs.xgamedev.net/en/docs/vs-arch), [Friflo](https://ecs.xgamedev.net/en/docs/vs-friflo), [DefaultEcs](https://ecs.xgamedev.net/en/docs/vs-defaultecs)) map the APIs side by side. ## Feature by feature Each row is one comparison: what it measures (linked to its section below), the time of EasyEcs, and the time of the fastest other library as a multiple of it, so 2× means that library takes twice as long. A library missing from a row has no such feature in its core package, or is not part of that comparison: the single operations run against Friflo only, the closest library on the full tick. The rows are sorted by the data, the biggest lead first, and a ratio marked "within error" is closer than the two rows' measurement errors added up. ### Clear leads The fastest other library takes at least 1.25 times as long as EasyEcs. | What is measured | EasyEcs | Next fastest | Its time vs EasyEcs | The others | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | ------------------------------------- | ------------------- | ----------------------------------------------------------------------------- | | [Save 10,000 entities and load them back](https://ecs.xgamedev.net/en/docs/comparison#saves) | 146 μs | DefaultEcs 4.33 ms, 4.37 MB allocated | 30× | Friflo.Engine.ECS 143×, 6.52 MB allocated | | [Add a component to 100,000 entities by query, then remove it](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 78.7 μs | Arch 1.21 ms | 15× | DefaultEcs 103×; Friflo.Engine.ECS 154×, 4.00 MB allocated | | [Spawn 10,000 entities beside 100,000, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 138 μs | Friflo.Engine.ECS 380 μs | 2.75× | Arch 2.96×; DefaultEcs 9.7×, 313 KB allocated | | [Query 100,000 players by value: a rating range, zone sums](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 127 μs | Friflo.Engine.ECS 317 μs | 2.49× | — | | [Create 1,000 parent-child squads, destroy them in cascade](https://ecs.xgamedev.net/en/docs/comparison#hierarchy) | 452 μs | Friflo.Engine.ECS 1.06 ms | 2.35× | — | | [Count 100 inventories through an index (1 item traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 425 ns | DefaultEcs 838 ns | 1.97× | Friflo.Engine.ECS 3.2× | | [Add a status component to 5% of 100,000 entities, then remove it](https://ecs.xgamedev.net/en/docs/comparison#operations) | 517 μs | Friflo.Engine.ECS 1.00 ms | 1.94× | — | | [Find the 10 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 507 ns | Arch 966 ns | 1.91× | Friflo.Engine.ECS 2.85×; DefaultEcs 73× | | [Spawn 5,000 entities from a prefab, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#operations) | 164 μs | Friflo.Engine.ECS 276 μs | 1.68× | — | | [Create 100,000 three-component entities one by one in a fresh world, room reserved first](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.60 ms, 3.44 MB allocated | Arch 4.21 ms, 4.62 MB allocated | 1.62× | Friflo.Engine.ECS 4.7×, 4.30 MB allocated | | [Iterate one component over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#operations) | 37.7 μs | Friflo.Engine.ECS 59.9 μs | 1.59× | — | | [Put 10,000 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 478 μs | DefaultEcs 745 μs | 1.56× | Friflo.Engine.ECS 1.67×; Arch 2.63× | | [Create 100,000 three-component entities in a fresh world in one call (the others' fastest way)](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.71 ms, 4.96 MB allocated | Arch 4.21 ms, 4.62 MB allocated | 1.56× | Friflo.Engine.ECS 4.5×, 4.30 MB allocated; DefaultEcs 6.3×, 19.1 MB allocated | | [Count 100 inventories through an index (100 items traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 5.11 μs | DefaultEcs 7.87 μs | 1.54× | Friflo.Engine.ECS 1.63× | | [Iterate with a filter: the players among 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#operations) | 11.3 μs | Friflo.Engine.ECS 16.6 μs | 1.46× | — | | [Find the 1,000 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 38.5 μs | Friflo.Engine.ECS 53.7 μs | 1.40× | DefaultEcs 2.01×; Arch 2.18× | | [Iterate with the entity handle of each row](https://ecs.xgamedev.net/en/docs/comparison#operations) | 49.0 μs | Friflo.Engine.ECS 67.2 μs | 1.37× | — | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Close EasyEcs ahead by less than that; the full server tick is one of these rows. | What is measured | EasyEcs | Next fastest | Its time vs EasyEcs | The others | | -------------------------------------------------------------------------------------------------------------------------------------- | ------- | ------------------------- | -------------------- | ------------------------------------------------------------------ | | [Four independent systems over 100,000 entities, one after another](https://ecs.xgamedev.net/en/docs/comparison#parallel) | 395 μs | DefaultEcs 471 μs | 1.19× | — | | [Rewire 100 of 10,000 friend lists, walk 100 follower sets](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 22.0 μs | Friflo.Engine.ECS 26.1 μs | 1.19× | — | | [Move 100,000 entities with SIMD over spans](https://ecs.xgamedev.net/en/docs/comparison#operations) | 69.5 μs | Friflo.Engine.ECS 80.7 μs | 1.16× | — | | [Create 5,000 entities one by one, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#operations) | 190 μs | Friflo.Engine.ECS 215 μs | 1.13× | — | | [Add and remove a tag in the passes that find them (1,000 of 100,000)](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | 163 μs | Friflo.Engine.ECS 183 μs | 1.12× | Arch 6.9×, 448 KB allocated; DefaultEcs 79× | | [Put 100 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 41.4 μs | Friflo.Engine.ECS 45.9 μs | 1.11× | Arch 2.00×; DefaultEcs 2.48× | | [Four independent systems over 100,000 entities, in parallel](https://ecs.xgamedev.net/en/docs/comparison#parallel) | 370 μs | DefaultEcs 405 μs | 1.09× (within error) | — | | [The full server tick: nine systems over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | 1.68 ms | Friflo.Engine.ECS 1.83 ms | 1.08× | Arch 3.4×, 535 KB allocated; DefaultEcs 3.7×, 60.9 KB allocated | | [Find the 1,000 of 100,000 entities that lost a component](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | 66.7 μs | Friflo.Engine.ECS 71.7 μs | 1.08× (within error) | DefaultEcs 1.61×; Arch 2.58× | | [The full server tick: nine systems over 10,000 entities](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | 175 μs | Friflo.Engine.ECS 183 μs | 1.05× (within error) | DefaultEcs 1.76×, 6.15 KB allocated; Arch 2.76×, 65.9 KB allocated | | [Iterate two components and a singleton](https://ecs.xgamedev.net/en/docs/comparison#operations) | 212 μs | Friflo.Engine.ECS 222 μs | 1.05× (within error) | — | | [Scan 100,000 entities for the 10 written, without a change filter](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 38.2 μs | Friflo.Engine.ECS 39.9 μs | 1.04× (within error) | Arch 2.40× | | [Move 100,000 entities: two components, per entity](https://ecs.xgamedev.net/en/docs/comparison#operations) | 253 μs | Friflo.Engine.ECS 257 μs | 1.02× (within error) | — | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Where another library is faster Each with the reason, read from the benchmark's source. | What is measured | EasyEcs | Faster library | Its time vs EasyEcs | Why | | ------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------- | ------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Iterate three components over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#operations) | 71.0 μs | Friflo.Engine.ECS 70.7 μs | 0.99× (within error) | The same span loop over the same dense columns in both libraries: the loop is bound by memory, not by the library. | | [Add and remove a tag in the passes that find them (10 of 100,000)](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | 78.2 μs | Friflo.Engine.ECS 75.4 μs | 0.96× (within error) | Friflo defers the changes to its command buffer, so both of its passes are plain span loops. A `[ForEach]` that may change structure checks after every row that its table did not move, and over 100,000 rows that costs more than 10 deferred changes; from about 1,000 changes on, applying them at once is faster. | | [Iterate in batches, reading entity ids only where needed](https://ecs.xgamedev.net/en/docs/comparison#operations) | 38.5 μs | Friflo.Engine.ECS 37.0 μs | 0.96× (within error) | The same loop over the same rows: Friflo's is written inline in the benchmark, EasyEcs' is generated from a batch `[ForEach]` method and runs as a system group. | | [Steer 100,000 agents on all cores (parallel query)](https://ecs.xgamedev.net/en/docs/comparison#parallel) | 766 μs | Arch 685 μs | 0.89× (within error) | Arch's and Friflo's runners keep worker threads of their own, which win when passes run back to back, as BenchmarkDotNet runs them. EasyEcs wakes thread-pool helpers only while they pay: in a real server tick a dedicated crew measured worse tail latency and more CPU per tick (D22). | | [Scan 100,000 entities for the 1,000 written, without a change filter](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 61.4 μs | Friflo.Engine.ECS 53.7 μs | 0.88× | Not the way to do it in EasyEcs: the component is `ITrackChanges`, so each of the 1,000 writes also stamps its row's change tick, which `[Changed]` needs and the scan ignores; Friflo's component is not tracked. `[Changed]` does the same job faster than every library's scan. | | [Find the 10 of 100,000 entities that lost a component](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | 830 ns | Friflo.Engine.ECS 697 ns | 0.84× (within error) | Friflo's `OnComponentRemoved` event pushes each id into a list you keep as the removal happens, a cost per removal; `[Removed]` finds the removals through per-block summaries, a fixed cost per pass that 10 removals do not cover. From 1,000 removals on, EasyEcs leads, with no subscription to write. | | [Create 100,000 three-component entities one by one in a fresh world, nothing reserved](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 7.13 ms, 8.97 MB allocated | Arch 4.77 ms, 4.84 MB allocated | 0.67× | A fresh EasyEcs world grows its table and entity storage by doubling, and the arrays past 85,000 bytes land on the large object heap; together they pass the budget that sets off a full collection, once per new world (D28). Arch keeps entities in 16 KB chunks, which never reach that heap. Reserve the table with `EnsureCapacity(count)` or create the entities with `CreateEntities`, and EasyEcs is the fastest of the four. | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. EasyEcs also does not run on Unity or runtimes older than .NET 10; the other three do. ## Features From each package's public API and the comparison ports, which compile against the real packages. | Feature | EasyEcs | Friflo.Engine.ECS | Arch | DefaultEcs | | ------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------- | ------------------------------------------ | ------------------------------------------------------ | | Storage | archetype tables, presence bits per column | archetypes | archetypes in chunks | a pool per component type | | Structural changes inside a query loop | ✅ immediate, each entity visited once | ❌ throws `StructuralChangeException`; `CommandBuffer` | ⚠️ not guarded; `CommandBuffer` | ⚠️ `useBuffer` sets or `EntityCommandRecorder` | | Tags | ✅ empty components; removing one flips a bit | ✅ `ITag` (part of the archetype) | ⚠️ empty structs, moved like any component | ❌ | | Singletons | ✅ `ISingletonComponent`, `[ForEach]` parameters | ⚠️ `UniqueEntity` | ❌ | ✅ `World.Set` / `Get` | | Systems, ordering, groups | ✅ `EcsSystem`, `[UpdateBefore]` / `[UpdateAfter]`, `ISystemGroup`, `UpdateInterval` | ✅ `SystemRoot`, `SystemGroup`, `QuerySystem` | ❌ in core (Arch.Extended) | ✅ `ISystem`, `SequentialSystem`, `AEntitySetSystem` | | Source-generated systems | ✅ `[ForEach]` → inlined struct jobs | ❌ | ❌ in core | ❌ | | Generated named API per component | ✅ `e.Position`, `HasX`, `SetX(...)`, `IsDead`, `world.Battle` | ❌ | ❌ | ❌ | | Compile-time analyzer | ✅ EECS002-EECS034, with code fixes | ❌ | ❌ | ❌ | | Chunk / span iteration | ✅ batch `[ForEach]` methods, `ForEachBatch` | ✅ `Chunks` | ✅ chunks | ✅ `ReadOnlySpan` per system | | Struct query jobs | ✅ `IForEach`, `IForEachEntity`, `IForEachBatch` | ✅ | ✅ `IForEach`, `InlineQuery` | – | | Bulk changes | ✅ `SetAll`, `RemoveAll`, `DisableAll`, `EnableAll` | ✅ `EntityBatch`, `ApplyBatch` | ✅ add / remove by query | ❌ | | Bulk create and destroy | ✅ `CreateEntities`, `DestroyEntities(filter)`, `Instantiate(prefab, span)` | ⚠️ `CreateEntityBatch`; delete per entity | ⚠️ destroy by query | ❌ | | Reserve a table before creating into it | ✅ `EnsureCapacity(n)` | ✅ `EnsureCapacity` on the store and the archetype | ✅ `EnsureCapacity(signature, n)` | – | | Prefabs | ✅ `Prefab`: data outside every world | ⚠️ an entity of the store, copied with `CloneEntity` | ❌ | ⚠️ an entity copied with `CopyTo(world)` | | Change tracking (rows written since a tick) | ✅ `ITrackChanges`, `[Changed]`, every `ref` write | ❌ | ❌ (events) | ✅ `WhenChanged()` after `NotifyChanged()` | | Removal detection | ✅ `[Removed]` | ⚠️ `OnComponentRemoved` events | ⚠️ `SubscribeComponentRemoved` events | ✅ `WhenRemoved()` sets | | Value index | ✅ `IIndexed`, ordered walks and ranges | ✅ `IIndexedComponent`, ranges | ❌ | ✅ `EntityMap`, `EntityMultiMap` | | Tables split by a value | ✅ `GroupBy` (`IGroup`) | – | – | – | | Relations with reverse lookup | ✅ indexed `EntityId`, multi-target `IRelation` | ✅ `ILinkComponent`, `ILinkRelation` | ❌ in core | ❌ | | Hierarchy | ✅ `ChildOf`, `Children`, cascading destroy | ✅ `AddChild`, `ChildEntities` | ❌ | ❌ | | Disable a component, keep its value | ✅ `Disable()` / `Enable()` | ⚠️ whole entity (`Enabled`) | ❌ | ⚠️ whole entity, or a component (`Disable()`) | | Parallel systems | ✅ conflict-free stages from generated access | ❌ | ❌ | ✅ `ParallelSystem` (you keep them independent) | | Parallel query | ✅ `[ForEach(Parallel = true)]`, analyzer-checked | ✅ `QueryJob`, `ParallelJobRunner` | ✅ `InlineParallelQuery`, `JobScheduler` | ✅ `DefaultParallelRunner` | | Snapshots in memory | ✅ `Capture` / `Restore` | ❌ | ❌ | ❌ | | Saves | ✅ binary `Save` / `Load` (Nino) | ✅ JSON | ❌ in core (Arch.Persistence) | ✅ text and binary | | Move entities to another world | ✅ `MoveEntities`, `SaveEntities` / `LoadEntities` | ✅ `CopyEntity` | ❌ | ✅ `CopyTo(world)` | | Unload a plugin's types | ✅ `RemoveTypes(assembly)` | – | – | – | | Per-system timing and error policy | ✅ `MeasureSystems`, `SystemErrorPolicy.Disable` | ✅ `SystemPerf` | ❌ | – | | Events (added, removed, created) | – (state changes are data) | ✅ | ✅ | ✅ | | Zero allocation per server tick | ✅ | ✅ | ❌ | ❌ | | Native AOT | ✅ (`IsAotCompatible`) | – | – | – | | Target frameworks | net10.0 | netstandard2.1, net6.0-8.0 | netstandard2.1, net6.0, net8.0 | netstandard1.1-2.1 | | Unity | ❌ | ✅ | ✅ | ✅ | ✅ built in · ⚠️ partly or with caveats · ❌ not available · – not applicable or not checked ## How changes are made The biggest difference is not speed but how a system changes the world. Friflo, Arch and DefaultEcs forbid (or do not guard) structural changes while a query iterates, so a system records them in a command buffer that is played back later: until then the entity still has its old components, and the order of effects depends on when buffers are flushed. EasyEcs applies every change at once, also in the middle of a pass over the same table, and still visits each entity at most once: ```csharp public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health hp) { if (hp.Value <= 0) unit.SetDead(); // applied now: later systems already see the corpse } } ``` The ports follow each library's model (Friflo and Arch play their command buffer back after every system that records changes), so the measured worlds behave the same. How EasyEcs makes immediate changes cheap is on [Why EasyEcs is fast](https://ecs.xgamedev.net/en/docs/why-fast#structural-changes). ## The same server tick A whole tick mixes every kind of work, so it shows what a real server gets, and it is closer than the single features: most of its time is iteration, where the loop is bound by memory. `EcsComparisonBenchmark` runs the headline world of EasyEcs (30% players, 70% NPCs, projectiles; movement, area of interest, combat, status effects, death, respawn, shooting) in each library, single-threaded. The EasyEcs side is `benchmarks/EasyEcs.Benchmark/WorldSimulation.cs` compiled unchanged; the others are `ArchSimulation.cs`, `FrifloSimulation.cs` and `DefaultEcsSimulation.cs`. Setup warms every world up for 200 ticks and checks that its counters (hits, deaths, spawns, area changes, entities) match an EasyEcs reference run within 5%: they cannot match exactly, because entity ids feed the random rolls and each library recycles ids in its own order. **100,000 entities** **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **10,000 entities** **One server tick of 10,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------ | ---------- | --------- | | EasyEcs 4.6 | 175 μs | 1.01× | 0 B | | Friflo.Engine.ECS 3.6 | 183 μs | 1.06× | 0 B | | DefaultEcs 0.17 | 307 μs | 1.77× | 6.15 KB | | Arch 2.1 | 482 μs | 2.78× | 65.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. EasyEcs and Friflo are close on this tick (Friflo takes 1.08× the time of EasyEcs at 100,000 entities, 1.06× at 10,000; the lead has changed between runs), and both allocate nothing per tick. Arch and DefaultEcs take 3.4× and 3.7× the time and allocate every tick (535 KB and 60.9 KB), mostly in their command buffers and entity sets. EasyEcs gains in the systems that add, remove and destroy (presence bits, no command buffer) and in those that pass the entity to the job. ## Operations `OperationBenchmark` isolates single operations of that world (100,000 entities), EasyEcs against Friflo, the closest peer on the tick. Every operation leaves the world as it found it. **Single operations, 100,000 entities: EasyEcs and Friflo.Engine.ECS** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------- | ------- | ---------- | --------- | | EasyEcs | Iterate1 | 37.7 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate1 | 59.9 μs | 1.59× | 0 B | | EasyEcs | Iterate2 | 253 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2 | 257 μs | 1.02× | 0 B | | EasyEcs | Iterate2Simd | 69.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2Simd | 80.7 μs | 1.16× | 0 B | | EasyEcs | Iterate3 | 71.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate3 | 70.7 μs | 0.99× | 0 B | | EasyEcs | With | 11.3 μs | 1.00× | 0 B | | Friflo.Engine.ECS | With | 16.6 μs | 1.46× | 0 B | | EasyEcs | Entity | 49.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Entity | 67.2 μs | 1.37× | 0 B | | EasyEcs | EntityBatch | 38.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | EntityBatch | 37.0 μs | 0.96× | 0 B | | EasyEcs | Singleton | 212 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Singleton | 222 μs | 1.05× | 0 B | | EasyEcs | Toggle | 517 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Toggle | 1.00 ms | 1.94× | 0 B | | EasyEcs | CreateDestroy | 190 μs | 1.00× | 0 B | | Friflo.Engine.ECS | CreateDestroy | 215 μs | 1.13× | 0 B | | EasyEcs | Instantiate | 164 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Instantiate | 276 μs | 1.68× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. - **Toggle** (stun 5% of the fighters, then recover them) is where presence bits pay: EasyEcs flips a bit and the entity keeps its row; Friflo moves it to another archetype and back through its command buffer. - **Instantiate** spawns 5,000 NPCs of six components: EasyEcs copies a `Prefab`'s row into consecutive rows at once, Friflo clones an entity of the store one by one (`CloneEntity`). - **Entity**: a per-entity job receives a handle built from the row's 8-byte `EntityId`; Friflo's `ForEachEntity` calls a delegate per entity. - **Ties**: two- and three-component iteration (`Iterate2`, `Iterate3`) and batched entity access (`EntityBatch`) come out even. Both libraries walk dense arrays there, and the loop is bound by memory, not by the library. ## Change tracking `ChangeTrackingComparison`: 100,000 entities, 10 (a quiet tick) or 1,000 of them get a new health per tick, and a system copies the changed healths into a replica. Each library uses its built-in feature where it has one (EasyEcs `[Changed]`, DefaultEcs `WhenChanged()` fed by `NotifyChanged()`), else a scan comparing values or a dirty tag added on write and removed after the copy. **10 written** **Replicate the 10 of 100,000 entities written this tick** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------- | ---------- | --------- | | EasyEcs | Changed | 507 ns | 1.00× | 0 B | | EasyEcs | Scan | 38.2 μs | 75× | 0 B | | DefaultEcs | WhenChanged | 37.1 μs | 73× | 0 B | | Friflo.Engine.ECS | Scan | 39.9 μs | 79× | 0 B | | Friflo.Engine.ECS | DirtyTag | 1.44 μs | 2.85× | 0 B | | Arch | Scan | 91.9 μs | 181× | 0 B | | Arch | DirtyTag | 966 ns | 1.91× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **1,000 written** **Replicate the 1,000 of 100,000 entities written this tick** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------- | ---------- | --------- | | EasyEcs | Changed | 38.5 μs | 1.00× | 0 B | | EasyEcs | Scan | 61.4 μs | 1.59× | 0 B | | DefaultEcs | WhenChanged | 77.3 μs | 2.01× | 0 B | | Friflo.Engine.ECS | Scan | 53.7 μs | 1.40× | 0 B | | Friflo.Engine.ECS | DirtyTag | 123 μs | 3.2× | 0 B | | Arch | Scan | 109 μs | 2.83× | 0 B | | Arch | DirtyTag | 84.0 μs | 2.18× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. `[Changed]` leads at both rates and needs no code at the write site: a write through `ref` is the change. A dirty tag is cheap when few entities change, but it moves each written entity between archetypes twice, so it falls behind a plain scan at 1,000 writes. A scan costs the whole table every tick, and `WhenChanged()` needs a `NotifyChanged()` next to every write. How the skipping works: [change-tick summaries](https://ecs.xgamedev.net/en/docs/why-fast#change-ticks). ## Removal detection `RemovalComparison`: 100,000 entities with a buff; per tick 10 or 1,000 buffs expire and the ones that expired the tick before come back, then every entity that lost its buff since the last tick is visited once. EasyEcs uses `[Removed]`, DefaultEcs a `WhenRemoved()` set completed after each tick, Friflo its `OnComponentRemoved` event collecting the ids, Arch a `Lost` tag added next to each removal. Setup checks that every removal is sent exactly once. **10 removed** **Send the 10 of 100,000 buffs that expired** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------- | ---------- | --------- | | EasyEcs | Removed | 830 ns | 1.00× | 0 B | | DefaultEcs | WhenRemoved | 39.6 μs | 48× | 0 B | | Friflo.Engine.ECS | Event | 697 ns | 0.84× | 0 B | | Arch | LostTag | 1.81 μs | 2.18× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **1,000 removed** **Send the 1,000 of 100,000 buffs that expired** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------- | ---------- | --------- | | EasyEcs | Removed | 66.7 μs | 1.00× | 0 B | | DefaultEcs | WhenRemoved | 107 μs | 1.61× | 0 B | | Friflo.Engine.ECS | Event | 71.7 μs | 1.08× | 0 B | | Arch | LostTag | 172 μs | 2.58× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. At 10 removals, Friflo's event (697 ns) is ahead of `[Removed]` (830 ns): it collects the ids in a callback as the removals happen, a cost per removal, while the EasyEcs pass finds them through per-block summaries, a fixed cost that 10 removals do not cover. At 1,000 removals, EasyEcs takes 66.7 μs and Friflo 71.7 μs. What EasyEcs gives in exchange: no subscription, no list kept by hand, and the removal is visible to any system that runs later, not only to the one callback. ## Indexes and relations `IndexComparison`: an inventory, 100,000 items each pointing at one of 1,000 owners; 1 or 100 items change hands, then 100 inventories are counted. EasyEcs uses an indexed `EntityId` (`IIndexed`), Friflo a link component (`GetIncomingLinks`), DefaultEcs an `EntityMultiMap`. Arch has no index in its core package. **1 trade** **1 trade, then 100 inventories counted** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | Index | 425 ns | 1.00× | 0 B | | Friflo.Engine.ECS | Links | 1.37 μs | 3.2× | 0 B | | DefaultEcs | MultiMap | 838 ns | 1.97× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **100 trades** **100 trades, then 100 inventories counted** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | Index | 5.11 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Links | 8.33 μs | 1.63× | 0 B | | DefaultEcs | MultiMap | 7.87 μs | 1.54× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. All three answer "which items does this owner hold" without a scan and update on every set. EasyEcs keeps relation heads in an array indexed by the owner's id, so neither a trade nor a count hashes anything; the hook in `Set` is one inlined call that the JIT removes for components without an index. `ValueQueryComparison`: 100,000 players with a rating and one of 16 zones; 1,000 ratings and 100 zones change, then the players rated 2,000-2,010 are counted and the gold of 4 zones summed. EasyEcs answers the zone with a group (a table per zone) or a value index, and the rating with an ordered index (`Range`); Friflo with `IIndexedComponent` and `ValueInRange`. **Rating ranges and zone sums over 100,000 players** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | ------ | ---------- | --------- | | EasyEcs | Group | 127 μs | 1.00× | 0 B | | EasyEcs | Index | 233 μs | 1.83× | 0 B | | Friflo.Engine.ECS | IndexedComponent | 317 μs | 2.49× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. `RelationComparison`: friend lists, 10,000 players following 8 others each; 100 players unfollow one and follow another, then the followers of 100 players are counted and walked. EasyEcs uses `IRelation` (a buffer of links per entity, indexed by target), Friflo `ILinkRelation`. **Rewire 100 of 10,000 friend lists, walk 100 follower sets** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------- | ------- | ---------- | --------- | | EasyEcs | Relations | 22.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | LinkRelations | 26.1 μs | 1.19× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Both libraries keep the same structure, a list of links per entity and an index by target, so the two are close (EasyEcs 22.0 μs, Friflo 26.1 μs). ## Hierarchy `HierarchyComparison`: 1,000 squads (a leader and 10 members) are created, then the leaders are destroyed with their members, in a warm world. EasyEcs creates the members in bulk as `ChildOf(leader)` and destroys the leaders with `DestroyEntities`, which cascades; Friflo's `DeleteEntity` detaches children, so the port deletes them first. Arch and DefaultEcs have no hierarchy. **Create and destroy 1,000 squads of 11** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | ChildOf | 452 μs | 1.00× | 0 B | | Friflo.Engine.ECS | AddChild | 1.06 ms | 2.35× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Disabling `DisableComparison`: 100,000 units; 100 or 10,000 fall asleep per operation and the previous ones wake up, then the vitality of the awake units is summed. EasyEcs uses an `Asleep` tag (a presence bit) or `Disable()`, which keeps the value while queries skip it; Friflo `entity.Enabled` (a `Disabled` tag, an archetype move); DefaultEcs `entity.Disable()`; Arch a tag and `WithNone`. **100 switched** | 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 | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **10,000 switched** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | ------- | ---------- | --------- | | EasyEcs | Tag | 478 μs | 1.00× | 0 B | | EasyEcs | DisableComponent | 563 μs | 1.18× | 0 B | | Friflo.Engine.ECS | Enabled | 797 μs | 1.67× | 0 B | | Arch | Tag | 1.26 ms | 2.63× | 0 B | | DefaultEcs | Disable | 745 μs | 1.56× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. At 100 switched, the sum dominates and Friflo's `Enabled` is close to EasyEcs. With frequent switching, moving entities between archetypes costs more than flipping bits, and the gap grows. ## Structural changes `StructuralChangeComparison`: 100,000 units; 10 or 1,000 lose their health, then one pass over the living marks those at zero as fallen (adds a tag) and a second pass revives them (removes it). EasyEcs changes structure inside the passes; the others record into their command buffers and play them back after each pass. **10 killed** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | --------------- | ------- | ---------- | --------- | | EasyEcs | Direct | 78.2 μs | 1.00× | 0 B | | Friflo.Engine.ECS | CommandBuffer | 75.4 μs | 0.96× | 0 B | | Arch | CommandBuffer | 184 μs | 2.36× | 5.30 KB | | DefaultEcs | CommandRecorder | 496 μs | 6.3× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **1,000 killed** | 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 | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Friflo's command buffer is close to the direct changes: most of the cost is the passes themselves. Arch's buffer allocates while it records and plays back. The DefaultEcs row at 1,000 carries an error as large as its mean in this run. ## Bulk changes and spawns `BulkChangeComparison`: 100,000 fighters are all stunned, then the stun is lifted from everyone. EasyEcs uses `SetAll` / `RemoveAll` (after the first round the stun keeps its column, so a round flips presence bits); Friflo an `EntityBatch` applied to a query; Arch add and remove by query (whole tables move); DefaultEcs has no bulk change and sets per entity. **Stun 100,000 fighters, then lift the stun** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | ------- | ---------- | --------- | | EasyEcs | SetAllRemoveAll | 78.7 μs | 1.00× | 0 B | | Friflo.Engine.ECS | ApplyBatch | 12.1 ms | 154× | 4.00 MB | | Arch | AddRemoveByQuery | 1.21 ms | 15× | 0 B | | DefaultEcs | PerEntity | 8.12 ms | 103× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. `BulkSpawnComparison`: 10,000 shots are spawned beside 100,000 fighters, then all cleared. EasyEcs uses `CreateEntities` (one table, rows placed at once) and `DestroyEntities()`; Friflo and DefaultEcs create and delete per entity; Arch creates per entity after `EnsureCapacity` and destroys by query. **Spawn 10,000 shots, then clear them** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------------------- | ------- | ---------- | --------- | | EasyEcs | CreateAndDestroyAll | 138 μs | 1.00× | 0 B | | Friflo.Engine.ECS | PerEntity | 380 μs | 2.75× | 0 B | | Arch | CreateAndDestroyByQuery | 409 μs | 2.96× | 0 B | | DefaultEcs | PerEntity | 1.33 ms | 9.7× | 313 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Creating entities in a fresh world `ColdCreateComparison`: 100,000 entities of one, two or three components created in a world that has never held any, a new world for every call: one by one (`PerEntity`), one by one after reserving room (`PerEntity_Reserved`: `EnsureCapacity(n)` in EasyEcs, `EnsureCapacity` on Friflo's store and archetype and on Arch's world; DefaultEcs has no tables to reserve), and in one `CreateEntities` call (`Bulk`, EasyEcs only). The comparisons above count three components: reserved against reserved, the bulk call against each library's fastest way, and one by one against one by one. **1 component** **Create 100,000 entities of one component in a fresh world** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------------ | ------- | ---------- | --------- | | EasyEcs | PerEntity | 5.99 ms | 1.00× | 6.97 MB | | Friflo.Engine.ECS | PerEntity | 15.3 ms | 2.56× | 7.99 MB | | Arch | PerEntity | 3.76 ms | 0.63× | 4.00 MB | | DefaultEcs | PerEntity | 13.1 ms | 2.19× | 11.1 MB | | EasyEcs | PerEntity_Reserved | 1.94 ms | 1.00× | 2.67 MB | | Friflo.Engine.ECS | PerEntity_Reserved | 11.3 ms | 5.8× | 3.29 MB | | Arch | PerEntity_Reserved | 3.45 ms | 1.78× | 3.85 MB | | EasyEcs | Bulk | 2.65 ms | 1.00× | 4.20 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **2 components** **Create 100,000 entities of two components in a fresh world** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------------ | ------- | ---------- | --------- | | EasyEcs | PerEntity | 6.35 ms | 1.00× | 7.97 MB | | Friflo.Engine.ECS | PerEntity | 14.1 ms | 2.22× | 8.99 MB | | Arch | PerEntity | 4.61 ms | 0.73× | 4.43 MB | | DefaultEcs | PerEntity | 15.0 ms | 2.36× | 15.1 MB | | EasyEcs | PerEntity_Reserved | 2.71 ms | 1.00× | 3.05 MB | | Friflo.Engine.ECS | PerEntity_Reserved | 12.2 ms | 4.5× | 3.80 MB | | Arch | PerEntity_Reserved | 3.77 ms | 1.39× | 4.24 MB | | EasyEcs | Bulk | 2.55 ms | 1.00× | 4.58 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **3 components** **Create 100,000 entities of three components in a fresh world** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------------ | ------- | ---------- | --------- | | EasyEcs | PerEntity | 7.13 ms | 1.00× | 8.97 MB | | Friflo.Engine.ECS | PerEntity | 15.4 ms | 2.15× | 9.99 MB | | Arch | PerEntity | 4.77 ms | 0.67× | 4.84 MB | | DefaultEcs | PerEntity | 16.9 ms | 2.38× | 19.1 MB | | EasyEcs | PerEntity_Reserved | 2.60 ms | 1.00× | 3.44 MB | | Friflo.Engine.ECS | PerEntity_Reserved | 12.3 ms | 4.7× | 4.30 MB | | Arch | PerEntity_Reserved | 4.21 ms | 1.62× | 4.62 MB | | EasyEcs | Bulk | 2.71 ms | 1.00× | 4.96 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **One by one with nothing reserved, Arch is faster** (EasyEcs takes 1.50× as long with three components). A fresh EasyEcs table and its entity storage grow by doubling; the large arrays land on the large object heap and set off a full collection once per new world. Arch's 16 KB chunks never reach that heap. Reserved, or in one call, nothing starts a collection and EasyEcs is the fastest of the four ([D28](https://ecs.xgamedev.net/en/docs/decisions#d28-reservations-grow-to-what-they-need-entity-storage-on-the-pinned-heap); what to write: [Performance](https://ecs.xgamedev.net/en/docs/performance#cold-create)). ## Parallel work `ParallelQueryComparison`: 100,000 agents steer towards the nearest of 16 waypoints on all cores. EasyEcs uses `[ForEach(Parallel = true)]`, Friflo a `QueryJob` with a `ParallelJobRunner`, Arch `InlineParallelQuery` on its job scheduler, DefaultEcs an `AEntitySetSystem` with a `DefaultParallelRunner`. **Steer 100,000 agents on all cores** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------------- | ------ | ---------- | --------- | | EasyEcs | Parallel | 766 μs | 1.00× | 0 B | | Friflo.Engine.ECS | QueryJob | 754 μs | 0.98× | 0 B | | Arch | InlineParallelQuery | 685 μs | 0.89× | 0 B | | DefaultEcs | ParallelRunner | 854 μs | 1.11× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **EasyEcs does not win this one**: Arch and Friflo (754 μs) come out ahead of EasyEcs (766 μs), within this run's error. Their runners keep worker threads of their own; EasyEcs runs on the calling thread plus thread-pool helpers that it wakes only while they pay. Measured back to back, as BenchmarkDotNet does, dedicated workers win; in a server tick where passes are milliseconds apart, a dedicated spinning crew measured worse in tail latency and CPU per tick ([D22](https://ecs.xgamedev.net/en/docs/decisions)), so EasyEcs keeps the thread pool. `ParallelSystemsComparison`: four independent systems over 100,000 entities, sequential and in parallel. DefaultEcs is the only peer that schedules whole systems in parallel (`ParallelSystem`); EasyEcs forms the stage from the systems' generated access, so you cannot put two conflicting systems in one by mistake. **Four independent systems over 100,000 entities** | Library | Parallel | Mean | vs EasyEcs | Allocated | | ---------- | -------- | ------ | ---------- | --------- | | EasyEcs | False | 395 μs | 1.00× | 0 B | | DefaultEcs | False | 471 μs | 1.19× | 0 B | | EasyEcs | True | 370 μs | 1.00× | 0 B | | DefaultEcs | True | 405 μs | 1.09× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. > **Parallel numbers** > > The reference machine has 4 cores, and the parallel rows of this run carry a large error. Read them as an order of magnitude; they may be re-measured. ## Saves `SaveComparison`: 10,000 units (a position and a stock each) are written and read back into a world. The formats differ: EasyEcs writes binary (Nino; unmanaged rows copied as raw bytes with a field hash), Friflo JSON, DefaultEcs its binary serializer into a new world. Arch saves through a separate package. **Save and load 10,000 units** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | SaveLoad | 146 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Json | 20.8 ms | 143× | 6.52 MB | | DefaultEcs | Binary | 4.33 ms | 30× | 4.37 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Their features in EasyEcs What the other libraries offer and how EasyEcs does the same job. Some are built in under another name; some are done with data instead of a mechanism (EasyEcs has no events or command buffers on purpose); a few are not offered. The [battle server example](https://ecs.xgamedev.net/en/docs/example) shows most of them. | Their feature | In | EasyEcs | | ----------------------------------------- | ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | Command buffer for changes during a query | Friflo, Arch, DefaultEcs | not needed: changes apply at once, also mid-pass | | Thread-safe command buffer | Friflo | a queue you own, drained by a system on the world's thread ([threading](https://ecs.xgamedev.net/en/docs/guide/threading)) | | Component added / removed / set events | Friflo, Arch, DefaultEcs | state changes are data: a component the next system queries | | `WhenChanged` sets and `NotifyChanged` | DefaultEcs | `[Changed]`, `QueryFilter.Changed(since)`: a `ref` write is the change | | `WhenRemoved` sets, removal events | DefaultEcs, Friflo, Arch | `[Removed]`, `QueryFilter.Removed(since)` | | Prefab entities, cloning | Friflo, DefaultEcs | `Prefab` and `world.Instantiate`; `entity.Clone()` for a living entity | | Tags | Friflo | empty components; removing one flips a bit | | Unique entity, world components | Friflo, DefaultEcs | singletons, as `[ForEach]` parameters or a `SingletonRef` | | Enable / disable an entity | Friflo, DefaultEcs | a tag (`[Without]`), or `Disable()` for one component | | Systems, groups, ordering | Friflo, DefaultEcs, Arch.Extended | `EcsSystem`, `[UpdateBefore]` / `[UpdateAfter]`, `ISystemGroup`, `UpdateInterval` | | Struct query jobs, chunk iteration | Arch, Friflo | `IForEach`, `IForEachEntity`, `IForEachBatch`; batch `[ForEach]` methods | | Parallel query | Friflo, Arch, DefaultEcs | `[ForEach(Parallel = true)]`, `ForEachParallel`, `ForEachEntityParallel` | | Parallel systems | DefaultEcs | `WorldOptions.ParallelSystems` | | Bulk changes | Friflo, Arch | `SetAll`, `RemoveAll`, `DisableAll`, `EnableAll`, `CreateEntities`, `DestroyEntities` | | Indexed components | Friflo, DefaultEcs | `IIndexed`: `Find`, `TryFind`, `Count`, ordered `Range` | | Links and relations | Friflo | an indexed `EntityId`, or `IRelation` for many targets | | Parent / child hierarchy | Friflo | `ChildOf`, `world.Children`, cascading destroy; no transform propagation | | Serialization | Friflo (JSON), DefaultEcs (text, binary) | binary `Save` / `Load`, plus in-memory `Capture` / `Restore` | | System performance monitor | Friflo | `WorldOptions.MeasureSystems`, `system.Stats` | | Shared components (`SetSameAs`) | DefaultEcs | not built in: keep shared data in a singleton and an id into it | | Unity, older runtimes | all three | not offered: net10.0 only | ## When to pick which library | Pick | When | | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **EasyEcs** | A .NET 10 server or simulation where state flips constantly and you want changes applied where they are decided, systems generated and checked at compile time, change and removal tracking, prefabs, indexes, relations, saves and snapshots built in, and nothing allocated per tick. | | **Friflo.Engine.ECS** | You need Unity or older runtimes, events, or JSON serialization, accept command buffers for changes during iteration, and want a fast general-purpose ECS. | | **Arch** | You need Unity or older runtimes and a small core with chunk-based storage, adding systems and generators from Arch.Extended. | | **DefaultEcs** | You need netstandard down to 1.1, reactive sets and built-in serializers, and the world is small enough that its per-tick allocations do not matter. | ## Related - [EasyEcs vs Friflo.Engine.ECS](https://ecs.xgamedev.net/en/docs/vs-friflo): The closest peer, concept by concept and number by number. - [EasyEcs vs Arch](https://ecs.xgamedev.net/en/docs/vs-arch): Command buffers against immediate changes, and the tick. - [EasyEcs vs DefaultEcs](https://ecs.xgamedev.net/en/docs/vs-defaultecs): Sparse pools and entity sets against archetype tables. - [Why EasyEcs is fast](https://ecs.xgamedev.net/en/docs/why-fast): The mechanisms behind the numbers. --- # EasyEcs vs Friflo.Engine.ECS > EasyEcs and Friflo.Engine.ECS side by side: how the concepts map, the same system in both, every benchmark between them, and when Friflo is the better choice. URL: https://ecs.xgamedev.net/en/docs/vs-friflo Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/vs-friflo.md [Friflo.Engine.ECS](https://github.com/friflo/Friflo.Engine.ECS) is the closest peer of EasyEcs: both are archetype ECS libraries that allocate nothing per server tick, both have tags, indexed components, relations and a hierarchy, and on the headline tick they are close. The differences are in the model. Friflo iterates chunks of a cached query and records structural changes in a command buffer; EasyEcs generates struct jobs from `[ForEach]` methods, applies changes immediately, keeps removed components' rows with presence bits, and tracks changes and removals as data instead of events. In the 35 head-to-head benchmarks both libraries take part in, EasyEcs is faster in 24, within the measurement error in 10 and slower in 1. On the same server tick of 100,000 entities, Friflo takes 1.08× the time of EasyEcs (1.06× at 10,000), and neither allocates per tick. Friflo also runs in Unity and on older .NET (netstandard2.1, net6.0-8.0); EasyEcs needs .NET 10. - Add a component to 100,000 entities by query, then remove it, vs Friflo.Engine.ECS: **154× faster**, EasyEcs 78.7 μs, Friflo.Engine.ECS 12.1 ms - Benchmarks EasyEcs is faster in: **24 / 35**, of those both libraries take part in, beyond the measurement error - Friflo's time for the server tick: **1.08×**, relative to EasyEcs, 100,000 entities BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## At a glance | | EasyEcs | Friflo.Engine.ECS | | ----------------------------- | ----------------------------------------------- | ---------------------------------------------------------- | | Storage | archetype tables, presence bits per column | archetypes | | Changes during a query | applied at once | `StructuralChangeException`; recorded in a `CommandBuffer` | | Removing a component or a tag | flips a bit, the entity keeps its row | moves the entity to another archetype | | Systems | `EcsSystem` with generated `[ForEach]` jobs | `SystemRoot`, `SystemGroup`, `QuerySystem` | | Change tracking | `[Changed]`: rows written since the last run | none (component events) | | Removal tracking | `[Removed]` | `OnComponentRemoved` events | | Saves | binary `Save` / `Load`, in-memory snapshots | JSON (`EntitySerializer`) | | Compile-time checks | analyzer EECS002-EECS034 with code fixes | none | | Runtimes | net10.0 | netstandard2.1, net6.0-8.0; Unity | ## Concepts side by side | Concept | Friflo.Engine.ECS | EasyEcs | | ----------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | World | `new EntityStore()` | `new World()` | | Component | `struct X : IComponent` | `struct X : IComponent` (namespace `EasyEcs`) | | Tag | `struct Dead : ITag`, `AddTag()` | `struct Dead : IComponent` (empty), `entity.SetDead()` | | Singleton | `UniqueEntity` | `ISingletonComponent`, `world.AddSingleton()` | | Create | `store.CreateEntity(a, b)` | `world.CreateEntity(a, b)` | | Reserve before creating | `store.EnsureCapacity(n)`, `archetype.EnsureCapacity(n)` | `world.EnsureCapacity(n)` | | Create many | `archetype.CreateEntity()` per entity, `CreateEntityBatch` | `world.CreateEntities(span, a, b)` | | Read, write | `entity.GetComponent()` (ref) | `entity.Hp` (ref, generated), `entity.Get()` in generic code | | Add, remove | `entity.AddComponent(c)`, `RemoveComponent()` | `entity.SetHp(…)`, `entity.RemoveHp()` | | Destroy | `entity.DeleteEntity()` | `entity.Destroy()`, `world.DestroyEntities(filter)` | | Query | `store.Query().WithoutAnyTags(Tags.Get())` | `[ForEach, Without]`; `QueryFilter.Create().Without()` | | Iterate | `foreach (var (as, bs, entities) in query.Chunks)` + `Span` loops | a `[ForEach]` method, or a batch method taking `Span` | | Entity per row | `query.ForEachEntity((ref A a, Entity e) => ...)` | an `Entity` parameter of a `[ForEach]` method | | Command buffer | `store.GetCommandBuffer()`, `Playback()` | none: changes apply at once | | Bulk change | `EntityBatch`, `query.Entities.ApplyBatch(batch)` | `world.SetAll(value, filter)`, `RemoveAll(filter)` | | Prefab | an entity of the store, `store.CloneEntity(e)` | `Prefab`, `world.Instantiate(prefab, span)` | | Disable | `entity.Enabled = false` | a tag and `[Without]`, or `entity.Disable()` | | Indexed component | `IIndexedComponent`, `store.ComponentIndex()[key]`, `ValueInRange` | `IIndexed`, `world.Index().Find(key)`, ordered `Range` | | Link to an entity | `ILinkComponent`, `GetIncomingLinks()` | an `EntityId` key (`IIndexed`), `index.Find(target)` | | Many links | `ILinkRelation`, `AddRelation`, `GetRelations()` | `IRelation`, `entity.AddRelation`, `world.Relations()` | | Hierarchy | `AddChild`, `ChildEntities` | `ChildOf(parent)`, `world.Children(parent)`, cascading destroy | | Removal callback | `store.OnComponentRemoved += ...` | `[Removed]` (no callback) | | Parallel query | `store.JobRunner = new ParallelJobRunner(n)`, `QueryJob.RunParallel()` | `[ForEach(Parallel = true)]` | | Save | `EntitySerializer.WriteStore` / `ReadIntoStore` (JSON) | `world.Save(writer)` / `world.Load(bytes)` (binary) | ## The same task in both The death check of the headline tick: units whose health ran out get a `Dead` tag and are counted. Friflo cannot add the tag while its query iterates, so the port records it and plays the buffer back after the system (`FrifloSimulation.cs`). **EasyEcs** ```csharp public struct Hp : IComponent { public int Value, Max; } public struct Npc : IComponent { public int TemplateId; } public struct Deaths : ISingletonComponent { public int Count, NpcKills; } public class DeathSystem : EcsSystem { [ForEach, Without] static void CheckDeath(Entity entity, in Hp hp, ref Deaths deaths) { if (hp.Value > 0) return; entity.SetDead(); // applied now deaths.Count++; if (entity.HasNpc) deaths.NpcKills++; } } ``` ```csharp world.AddSingleton(); world.AddSystem(); world.Update(); ``` **Friflo.Engine.ECS** ```csharp var alive = store.Query().WithoutAnyTags(Tags.Get()); var buffer = store.GetCommandBuffer(); buffer.ReuseBuffer = true; foreach (var (hps, entities) in alive.Chunks) { var hp = hps.Span; for (int i = 0; i < hp.Length; i++) { if (hp[i].Value > 0) continue; buffer.AddTag(entities.Ids[i]); // recorded counters.Deaths++; if (entities.EntityAt(i).HasComponent()) counters.NpcKills++; } } buffer.Playback(); // applied here ``` The counters live in a singleton that the generated job resolves once per pass. Because the `Dead` tag is applied at once, a later system in the same update already skips the corpse. ## The numbers Every comparison both libraries take part in, sorted by lead (each row links to its section of [the comparison](https://ecs.xgamedev.net/en/docs/comparison)): | What is measured | EasyEcs | Friflo.Engine.ECS | Its time vs EasyEcs | Why | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -------------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Add a component to 100,000 entities by query, then remove it](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 78.7 μs | 12.1 ms, 4.00 MB allocated | 154× | | | [Save 10,000 entities and load them back](https://ecs.xgamedev.net/en/docs/comparison#saves) | 146 μs | 20.8 ms, 6.52 MB allocated | 143× | | | [Create 100,000 three-component entities one by one in a fresh world, room reserved first](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.60 ms, 3.44 MB allocated | 12.3 ms, 4.30 MB allocated | 4.7× | | | [Create 100,000 three-component entities in a fresh world in one call (the others' fastest way)](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.71 ms, 4.96 MB allocated | 12.3 ms, 4.30 MB allocated | 4.5× | | | [Count 100 inventories through an index (1 item traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 425 ns | 1.37 μs | 3.2× | | | [Find the 10 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 507 ns | 1.44 μs | 2.85× | | | [Spawn 10,000 entities beside 100,000, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 138 μs | 380 μs | 2.75× | | | [Query 100,000 players by value: a rating range, zone sums](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 127 μs | 317 μs | 2.49× | | | [Create 1,000 parent-child squads, destroy them in cascade](https://ecs.xgamedev.net/en/docs/comparison#hierarchy) | 452 μs | 1.06 ms | 2.35× | | | [Create 100,000 three-component entities one by one in a fresh world, nothing reserved](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 7.13 ms, 8.97 MB allocated | 15.4 ms, 9.99 MB allocated | 2.15× | | | [Add a status component to 5% of 100,000 entities, then remove it](https://ecs.xgamedev.net/en/docs/comparison#operations) | 517 μs | 1.00 ms | 1.94× | | | [Spawn 5,000 entities from a prefab, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#operations) | 164 μs | 276 μs | 1.68× | | | [Put 10,000 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 478 μs | 797 μs | 1.67× | | | [Count 100 inventories through an index (100 items traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 5.11 μs | 8.33 μs | 1.63× | | | [Iterate one component over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#operations) | 37.7 μs | 59.9 μs | 1.59× | | | [Iterate with a filter: the players among 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#operations) | 11.3 μs | 16.6 μs | 1.46× | | | [Find the 1,000 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 38.5 μs | 53.7 μs | 1.40× | | | [Iterate with the entity handle of each row](https://ecs.xgamedev.net/en/docs/comparison#operations) | 49.0 μs | 67.2 μs | 1.37× | | | [Rewire 100 of 10,000 friend lists, walk 100 follower sets](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 22.0 μs | 26.1 μs | 1.19× | | | [Move 100,000 entities with SIMD over spans](https://ecs.xgamedev.net/en/docs/comparison#operations) | 69.5 μs | 80.7 μs | 1.16× | | | [Create 5,000 entities one by one, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#operations) | 190 μs | 215 μs | 1.13× | | | [Add and remove a tag in the passes that find them (1,000 of 100,000)](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | 163 μs | 183 μs | 1.12× | | | [Put 100 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 41.4 μs | 45.9 μs | 1.11× | | | [The full server tick: nine systems over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | 1.68 ms | 1.83 ms | 1.08× | | | [Find the 1,000 of 100,000 entities that lost a component](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | 66.7 μs | 71.7 μs | 1.08× (within error) | | | [The full server tick: nine systems over 10,000 entities](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | 175 μs | 183 μs | 1.05× (within error) | | | [Iterate two components and a singleton](https://ecs.xgamedev.net/en/docs/comparison#operations) | 212 μs | 222 μs | 1.05× (within error) | | | [Scan 100,000 entities for the 10 written, without a change filter](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 38.2 μs | 39.9 μs | 1.04× (within error) | | | [Move 100,000 entities: two components, per entity](https://ecs.xgamedev.net/en/docs/comparison#operations) | 253 μs | 257 μs | 1.02× (within error) | | | [Iterate three components over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#operations) | 71.0 μs | 70.7 μs | 0.99× (within error) | The same span loop over the same dense columns in both libraries: the loop is bound by memory, not by the library. | | [Steer 100,000 agents on all cores (parallel query)](https://ecs.xgamedev.net/en/docs/comparison#parallel) | 766 μs | 754 μs | 0.98× (within error) | Arch's and Friflo's runners keep worker threads of their own, which win when passes run back to back, as BenchmarkDotNet runs them. EasyEcs wakes thread-pool helpers only while they pay: in a real server tick a dedicated crew measured worse tail latency and more CPU per tick (D22). | | [Add and remove a tag in the passes that find them (10 of 100,000)](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | 78.2 μs | 75.4 μs | 0.96× (within error) | Friflo defers the changes to its command buffer, so both of its passes are plain span loops. A `[ForEach]` that may change structure checks after every row that its table did not move, and over 100,000 rows that costs more than 10 deferred changes; from about 1,000 changes on, applying them at once is faster. | | [Iterate in batches, reading entity ids only where needed](https://ecs.xgamedev.net/en/docs/comparison#operations) | 38.5 μs | 37.0 μs | 0.96× (within error) | The same loop over the same rows: Friflo's is written inline in the benchmark, EasyEcs' is generated from a batch `[ForEach]` method and runs as a system group. | | [Scan 100,000 entities for the 1,000 written, without a change filter](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 61.4 μs | 53.7 μs | 0.88× | Not the way to do it in EasyEcs: the component is `ITrackChanges`, so each of the 1,000 writes also stamps its row's change tick, which `[Changed]` needs and the scan ignores; Friflo's component is not tracked. `[Changed]` does the same job faster than every library's scan. | | [Find the 10 of 100,000 entities that lost a component](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | 830 ns | 697 ns | 0.84× (within error) | Friflo's `OnComponentRemoved` event pushes each id into a list you keep as the removal happens, a cost per removal; `[Removed]` finds the removals through per-block summaries, a fixed cost per pass that 10 removals do not cover. From 1,000 removals on, EasyEcs leads, with no subscription to write. | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The headline tick: **100,000 entities** **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **10,000 entities** **One server tick of 10,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------ | ---------- | --------- | | EasyEcs 4.6 | 175 μs | 1.01× | 0 B | | Friflo.Engine.ECS 3.6 | 183 μs | 1.06× | 0 B | | DefaultEcs 0.17 | 307 μs | 1.77× | 6.15 KB | | Arch 2.1 | 482 μs | 2.78× | 65.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Friflo takes 1.08× the time of EasyEcs at 100,000 entities and 1.06× at 10,000. The two have traded the lead between runs on the same machine, so read this as "even", with the per-operation breakdown showing where each one gains: **Single operations of the headline world, 100,000 entities** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------- | ------- | ---------- | --------- | | EasyEcs | Iterate1 | 37.7 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate1 | 59.9 μs | 1.59× | 0 B | | EasyEcs | Iterate2 | 253 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2 | 257 μs | 1.02× | 0 B | | EasyEcs | Iterate2Simd | 69.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2Simd | 80.7 μs | 1.16× | 0 B | | EasyEcs | Iterate3 | 71.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate3 | 70.7 μs | 0.99× | 0 B | | EasyEcs | With | 11.3 μs | 1.00× | 0 B | | Friflo.Engine.ECS | With | 16.6 μs | 1.46× | 0 B | | EasyEcs | Entity | 49.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Entity | 67.2 μs | 1.37× | 0 B | | EasyEcs | EntityBatch | 38.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | EntityBatch | 37.0 μs | 0.96× | 0 B | | EasyEcs | Singleton | 212 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Singleton | 222 μs | 1.05× | 0 B | | EasyEcs | Toggle | 517 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Toggle | 1.00 ms | 1.94× | 0 B | | EasyEcs | CreateDestroy | 190 μs | 1.00× | 0 B | | Friflo.Engine.ECS | CreateDestroy | 215 μs | 1.13× | 0 B | | EasyEcs | Instantiate | 164 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Instantiate | 276 μs | 1.68× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Toggling a status and spawning from a prefab are where EasyEcs gains (presence bits, one row copy per instance); plain two- and three-component iteration and batched entity access are even. Features both libraries have: **Removals** **Send the buffs that expired: 10 or 1,000 of 100,000** | Library | Case | Removed | Mean | vs EasyEcs | Allocated | | ----------------- | ------- | ------- | ------- | ---------- | --------- | | EasyEcs | Removed | 10 | 830 ns | 1.00× | 0 B | | EasyEcs | Removed | 1000 | 66.7 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Event | 10 | 697 ns | 0.84× | 0 B | | Friflo.Engine.ECS | Event | 1000 | 71.7 μs | 1.08× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Changes** **Replicate the entities written this tick: 10 or 1,000 of 100,000** | Library | Case | Written | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ------- | ---------- | --------- | | EasyEcs | Changed | 10 | 507 ns | 1.00× | 0 B | | EasyEcs | Changed | 1000 | 38.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | DirtyTag | 10 | 1.44 μs | 2.85× | 0 B | | Friflo.Engine.ECS | DirtyTag | 1000 | 123 μs | 3.2× | 0 B | | Friflo.Engine.ECS | Scan | 10 | 39.9 μs | 79× | 0 B | | Friflo.Engine.ECS | Scan | 1000 | 53.7 μs | 1.40× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Relations** **Rewire 100 of 10,000 friend lists, walk 100 follower sets** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------- | ------- | ---------- | --------- | | EasyEcs | Relations | 22.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | LinkRelations | 26.1 μs | 1.19× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Create and destroy 1,000 squads of 11** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | ChildOf | 452 μs | 1.00× | 0 B | | Friflo.Engine.ECS | AddChild | 1.06 ms | 2.35× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Indexes** **Trades, then 100 inventories counted** | Library | Case | Trades | Mean | vs EasyEcs | Allocated | | ----------------- | ----- | ------ | ------- | ---------- | --------- | | EasyEcs | Index | 1 | 425 ns | 1.00× | 0 B | | EasyEcs | Index | 100 | 5.11 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Links | 1 | 1.37 μs | 3.2× | 0 B | | Friflo.Engine.ECS | Links | 100 | 8.33 μs | 1.63× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Rating ranges and zone sums over 100,000 players** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | ------ | ---------- | --------- | | EasyEcs | Group | 127 μs | 1.00× | 0 B | | EasyEcs | Index | 233 μs | 1.83× | 0 B | | Friflo.Engine.ECS | IndexedComponent | 317 μs | 2.49× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Units fall asleep and wake up, then the awake are summed** | Library | Case | Switched | Mean | vs EasyEcs | Allocated | | ----------------- | ---------------- | -------- | ------- | ---------- | --------- | | EasyEcs | Tag | 100 | 42.4 μs | 1.00× | 0 B | | EasyEcs | Tag | 10000 | 478 μs | 1.00× | 0 B | | EasyEcs | DisableComponent | 100 | 41.4 μs | 0.98× | 0 B | | EasyEcs | DisableComponent | 10000 | 563 μs | 1.18× | 0 B | | Friflo.Engine.ECS | Enabled | 100 | 45.9 μs | 1.08× | 0 B | | Friflo.Engine.ECS | Enabled | 10000 | 797 μs | 1.67× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Stun 100,000 fighters, then lift the stun** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | --------------- | ------- | ---------- | --------- | | EasyEcs | SetAllRemoveAll | 78.7 μs | 1.00× | 0 B | | Friflo.Engine.ECS | ApplyBatch | 12.1 ms | 154× | 4.00 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Mark the dead and revive them during two passes over 100,000 units** | Library | Case | Killed | Mean | vs EasyEcs | Allocated | | ----------------- | ------------- | ------ | ------- | ---------- | --------- | | EasyEcs | Direct | 10 | 78.2 μs | 1.00× | 0 B | | EasyEcs | Direct | 1000 | 163 μs | 1.00× | 0 B | | Friflo.Engine.ECS | CommandBuffer | 10 | 75.4 μs | 0.96× | 0 B | | Friflo.Engine.ECS | CommandBuffer | 1000 | 183 μs | 1.12× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Save and load 10,000 units** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | -------- | ------- | ---------- | --------- | | EasyEcs | SaveLoad | 146 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Json | 20.8 ms | 143× | 6.52 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## What Friflo does better - **Removal callbacks at small counts.** Friflo's `OnComponentRemoved` reports 10 removals in 697 ns against 830 ns for `[Removed]`: the callback collects the ids as removals happen. At 1,000 removals they are even. - **Relations.** On the friend-list benchmark Friflo is slightly ahead (26.1 μs against 22.0 μs), within the error: both keep a list of links per entity and an index by target. - **The parallel query.** Friflo's `ParallelJobRunner` (754 μs) is ahead of a parallel `[ForEach]` (766 μs) in this run, whose parallel rows carry a large error. Friflo keeps worker threads of its own; EasyEcs wakes thread-pool helpers only while they pay ([D22](https://ecs.xgamedev.net/en/docs/decisions)). - **Reach and tooling.** Unity, netstandard2.1 and net6.0-8.0, events, a thread-safe `CommandBufferSynced` and JSON serialization. ## When to choose Friflo Choose Friflo when you need Unity or a runtime older than .NET 10, want events or JSON, or prefer explicit chunk loops and a command buffer. Choose EasyEcs for a .NET 10 server where you want changes applied where they are decided, systems written as one method each and checked at compile time, change tracking without dirty tags, and binary saves and snapshots built in. Porting a Friflo codebase: [Migrate from Friflo.Engine.ECS](https://ecs.xgamedev.net/en/docs/migrate-from-friflo). ## Related - [Migrate from Friflo.Engine.ECS](https://ecs.xgamedev.net/en/docs/migrate-from-friflo): The API mapping and a whole simulation ported, step by step. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): Every benchmark against Friflo.Engine.ECS, Arch and DefaultEcs. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): `[Changed]` and `[Removed]` in depth. --- # EasyEcs vs Arch > EasyEcs and Arch side by side: how the concepts map, the same systems in both, the measured server tick and features, and when Arch is the better choice. URL: https://ecs.xgamedev.net/en/docs/vs-arch Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/vs-arch.md [Arch](https://github.com/genaray/Arch) and EasyEcs are both archetype ECS libraries for C#: entities with the same components share a table, and queries walk its columns. They differ in what the core does for you. Arch is a small, fast core: queries, struct jobs, chunks and a command buffer, with systems and source generators in the separate Arch.Extended packages. EasyEcs puts systems, generated jobs, change tracking, indexes, relations, saves and snapshots in one package for .NET 10 servers, and applies structural changes immediately instead of through a command buffer. In the 18 head-to-head benchmarks both libraries take part in, EasyEcs is faster in 16, within the measurement error in 1 and slower in 1. On the same server tick of 100,000 entities, Arch takes 3.4× the time of EasyEcs and allocates 535 KB per tick, where EasyEcs allocates 0 B. Arch runs on more runtimes (netstandard2.1, net6.0, net8.0 and Unity); EasyEcs needs .NET 10. - Add a component to 100,000 entities by query, then remove it, vs Arch: **15× faster**, EasyEcs 78.7 μs, Arch 1.21 ms - Benchmarks EasyEcs is faster in: **16 / 18**, of those both libraries take part in, beyond the measurement error - Arch's time for the server tick: **3.4×**, relative to EasyEcs, 100,000 entities - Arch allocates per tick: **535 KB**, EasyEcs allocates 0 B BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## At a glance | | EasyEcs | Arch | | ----------------------------- | -------------------------------------------- | ------------------------------------------------------------- | | Storage | archetype tables, presence bits per column | archetypes in chunks | | Changes during a query | applied at once | recorded in a `CommandBuffer`, played back later | | Removing a component | flips a bit, the entity keeps its row | moves the entity to another archetype | | Systems | built in, generated from `[ForEach]` methods | Arch.Extended | | Change and removal tracking | `[Changed]`, `[Removed]` | events (`SubscribeComponentSet`, `SubscribeComponentRemoved`) | | Indexes, relations, hierarchy | built in | relations in a separate package | | Allocation per server tick | none | the command buffer allocates | | Runtimes | net10.0 | netstandard2.1, net6.0, net8.0; Unity | ## Concepts side by side | Concept | Arch | EasyEcs | | ----------------------- | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | World | `World.Create()`, `World.Destroy(world)` | `new World()`, `world.Dispose()` | | Component | any struct | a struct implementing `IComponent` | | Tag | an empty struct | an empty struct implementing `IComponent` | | Singleton | none (a component on one entity) | `ISingletonComponent`, `world.AddSingleton()` | | Query | `new QueryDescription().WithAll().WithNone()` | `[ForEach, Without]` on a method; `QueryFilter.Create().Without()` for ad-hoc calls | | Struct job | `IForEach` with `Update(ref A, ref B)`, run by `world.InlineQuery(in query, ref job)` | `IForEach` with `Execute(ref A, ref B)`, run by `world.ForEach(ref job, in filter)` | | Job with the entity | `IForEachWithEntity`, `InlineEntityQuery` | `IForEachEntity`, `ForEachEntity`, or an `Entity` parameter of a `[ForEach]` method | | Chunks | `world.Query(in query).GetChunkIterator()`, then `chunk.GetSpan()` | batch `[ForEach]` methods taking `Span`, or `ForEachBatch` | | System | Arch.Extended `BaseSystem` | `EcsSystem` with `[ForEach]` methods | | Command buffer | `CommandBuffer`, `Playback(world)` | none: `entity.SetFire(10)`, `RemoveFire()`, `Destroy()` apply at once | | Bulk change | `world.Add(in query, value)`, `world.Remove(in query)` | `world.SetAll(value, filter)`, `world.RemoveAll(filter)` | | Reserve before creating | `world.EnsureCapacity(in signature, n)` | `world.EnsureCapacity(n)`, or `world.CreateEntities(span, a, b)` at once | | Parallel query | `World.SharedJobScheduler`, `InlineParallelQuery` | `[ForEach(Parallel = true)]` | | Events | `SubscribeComponentAdded` / `Removed` / `Set` | none: `[Changed]`, `[Removed]`, tags queried by later systems | ## The same task in both The combat system of the headline tick: fighters attack on a cooldown and some hits set the target on fire. Arch cannot add `Burning` while its query iterates, so the port records the change and plays it back after the system (`ArchSimulation.cs`). EasyEcs adds it on the spot (`WorldSimulation.cs`). **EasyEcs** ```csharp public struct Attack : IComponent { public int Damage, Cooldown, Interval; } public struct Hp : IComponent { public int Value, Max; } public struct Fire : IComponent { public int Ticks; } public class CombatSystem : EcsSystem { [ForEach, Without, Without] static void Fight(Entity entity, ref Attack attack, ref Hp hp) { if (--attack.Cooldown > 0) return; attack.Cooldown = attack.Interval; hp.Value -= attack.Damage; if (entity.Id.Index % 20 == 0 && !entity.HasFire) entity.SetFire(10); // applied now, also mid-pass } } ``` ```csharp world.AddSystem(); world.Update(); ``` **Arch** ```csharp private static readonly QueryDescription Fighters = new QueryDescription().WithAll().WithNone(); private struct Fight : IForEachWithEntity { public World W; public CommandBuffer B; public void Update(Entity e, ref Attack attack, ref Hp hp) { if (--attack.Cooldown > 0) return; attack.Cooldown = attack.Interval; hp.Value -= attack.Damage; if (e.Id % 20 == 0 && !W.Has(e)) B.Add(e, new Fire { Ticks = 10 }); // recorded } } var fight = new Fight { W = world, B = buffer }; world.InlineEntityQuery(in Fighters, ref fight); buffer.Playback(world); // applied here ``` In EasyEcs the filter, the job struct and the call are generated from the method; the system's access (writes `Attack` and `Hp`) is generated too, and the analyzer rejects a method that would break it. ## The numbers Every comparison both libraries take part in, sorted by lead (each row links to its section of [the comparison](https://ecs.xgamedev.net/en/docs/comparison)): | What is measured | EasyEcs | Arch | Its time vs EasyEcs | Why | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Add a component to 100,000 entities by query, then remove it](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 78.7 μs | 1.21 ms | 15× | | | [Add and remove a tag in the passes that find them (1,000 of 100,000)](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | 163 μs | 1.12 ms, 448 KB allocated | 6.9× | | | [The full server tick: nine systems over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | 1.68 ms | 5.76 ms, 535 KB allocated | 3.4× | | | [Spawn 10,000 entities beside 100,000, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 138 μs | 409 μs | 2.96× | | | [The full server tick: nine systems over 10,000 entities](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | 175 μs | 482 μs, 65.9 KB allocated | 2.76× | | | [Put 10,000 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 478 μs | 1.26 ms | 2.63× | | | [Find the 1,000 of 100,000 entities that lost a component](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | 66.7 μs | 172 μs | 2.58× | | | [Scan 100,000 entities for the 10 written, without a change filter](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 38.2 μs | 91.9 μs | 2.40× | | | [Add and remove a tag in the passes that find them (10 of 100,000)](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | 78.2 μs | 184 μs, 5.30 KB allocated | 2.36× | | | [Find the 10 of 100,000 entities that lost a component](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | 830 ns | 1.81 μs | 2.18× | | | [Find the 1,000 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 38.5 μs | 84.0 μs | 2.18× | | | [Put 100 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 41.4 μs | 82.8 μs | 2.00× | | | [Find the 10 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 507 ns | 966 ns | 1.91× | | | [Scan 100,000 entities for the 1,000 written, without a change filter](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 61.4 μs | 109 μs | 1.77× | | | [Create 100,000 three-component entities one by one in a fresh world, room reserved first](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.60 ms, 3.44 MB allocated | 4.21 ms, 4.62 MB allocated | 1.62× | | | [Create 100,000 three-component entities in a fresh world in one call (the others' fastest way)](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.71 ms, 4.96 MB allocated | 4.21 ms, 4.62 MB allocated | 1.56× | | | [Steer 100,000 agents on all cores (parallel query)](https://ecs.xgamedev.net/en/docs/comparison#parallel) | 766 μs | 685 μs | 0.89× (within error) | Arch's and Friflo's runners keep worker threads of their own, which win when passes run back to back, as BenchmarkDotNet runs them. EasyEcs wakes thread-pool helpers only while they pay: in a real server tick a dedicated crew measured worse tail latency and more CPU per tick (D22). | | [Create 100,000 three-component entities one by one in a fresh world, nothing reserved](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 7.13 ms, 8.97 MB allocated | 4.77 ms, 4.84 MB allocated | 0.67× | A fresh EasyEcs world grows its table and entity storage by doubling, and the arrays past 85,000 bytes land on the large object heap; together they pass the budget that sets off a full collection, once per new world (D28). Arch keeps entities in 16 KB chunks, which never reach that heap. Reserve the table with `EnsureCapacity(count)` or create the entities with `CreateEntities`, and EasyEcs is the fastest of the four. | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The headline tick, the same rules in both libraries, checked to produce the same counters: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Arch takes 3.4× the time of EasyEcs on this tick and allocates 535 KB per tick, most of it in its command buffer, which pools and regrows lists while it records and plays back. **Mark 1,000 of 100,000 units dead and revive them during two passes** | Library | Case | Mean | vs EasyEcs | Allocated | | ------- | ------------- | ------- | ---------- | --------- | | EasyEcs | Direct | 163 μs | 1.00× | 0 B | | Arch | CommandBuffer | 1.12 ms | 6.9× | 448 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Replicate the 1,000 of 100,000 entities written this tick** | Library | Case | Mean | vs EasyEcs | Allocated | | ------- | -------- | ------- | ---------- | --------- | | EasyEcs | Changed | 38.5 μs | 1.00× | 0 B | | Arch | DirtyTag | 84.0 μs | 2.18× | 0 B | | Arch | Scan | 109 μs | 2.83× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **10,000 of 100,000 units fall asleep and wake up, then the awake are summed** | Library | Case | Mean | vs EasyEcs | Allocated | | ------- | ---- | ------- | ---------- | --------- | | EasyEcs | Tag | 478 μs | 1.00× | 0 B | | Arch | Tag | 1.26 ms | 2.63× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Stun 100,000 fighters, then lift the stun** | Library | Case | Mean | vs EasyEcs | Allocated | | ------- | ---------------- | ------- | ---------- | --------- | | EasyEcs | SetAllRemoveAll | 78.7 μs | 1.00× | 0 B | | Arch | AddRemoveByQuery | 1.21 ms | 15× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Create 100,000 entities of three components in a fresh world** | Library | Case | Mean | vs EasyEcs | Allocated | | ------- | ------------------ | ------- | ---------- | --------- | | EasyEcs | PerEntity | 7.13 ms | 1.00× | 8.97 MB | | Arch | PerEntity | 4.77 ms | 0.67× | 4.84 MB | | EasyEcs | PerEntity_Reserved | 2.60 ms | 1.00× | 3.44 MB | | Arch | PerEntity_Reserved | 4.21 ms | 1.62× | 4.62 MB | | EasyEcs | Bulk | 2.71 ms | 1.00× | 4.96 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Steer 100,000 agents on all cores** | Library | Case | Mean | vs EasyEcs | Allocated | | ------- | ------------------- | ------ | ---------- | --------- | | EasyEcs | Parallel | 766 μs | 1.00× | 0 B | | Arch | InlineParallelQuery | 685 μs | 0.89× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Every other result, including the ones without Arch (Arch has no value index, hierarchy or save in its core), is on [the comparison page](https://ecs.xgamedev.net/en/docs/comparison). ## What Arch does better - **The parallel query.** `InlineParallelQuery` on Arch's job scheduler is ahead of EasyEcs' parallel `[ForEach]` in this run: the scheduler keeps worker threads of its own, which wins when passes run back to back. EasyEcs chose thread-pool helpers woken only while they pay ([D22](https://ecs.xgamedev.net/en/docs/decisions)); the parallel numbers of this run carry a large error. - **Filling a fresh world without a reservation.** Created one by one in a new world, Arch's entities take 4.77 ms against EasyEcs' 7.13 ms: EasyEcs' doubling arrays reach the large object heap and start a full collection, Arch's 16 KB chunks never do. Reserve the table first (`EnsureCapacity(n)`) or create in one call, and EasyEcs is ahead ([creating entities in a fresh world](https://ecs.xgamedev.net/en/docs/performance#cold-create)). - **Reach.** Arch runs on netstandard2.1, net6.0 and net8.0, and in Unity. EasyEcs needs .NET 10. - **A small core.** If you want queries and storage and nothing else, Arch's core is smaller; systems, relations and persistence are packages you add when you need them. - **Events.** Arch raises component and entity events; EasyEcs has none by design ([D1](https://ecs.xgamedev.net/en/docs/decisions)). ## When to choose Arch Choose Arch when you need Unity or a runtime older than .NET 10, want a minimal core and are happy to assemble systems and tooling from Arch.Extended. Choose EasyEcs for a .NET 10 server whose state changes every tick: changes applied where they are decided, generated and analyzer-checked systems, change and removal tracking, and no allocation per tick. Porting an Arch codebase: [Migrate from Arch](https://ecs.xgamedev.net/en/docs/migrate-from-arch). ## Related - [Migrate from Arch](https://ecs.xgamedev.net/en/docs/migrate-from-arch): The API mapping and a whole simulation ported, step by step. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): Every benchmark against Arch, Friflo.Engine.ECS and DefaultEcs. - [Why EasyEcs is fast](https://ecs.xgamedev.net/en/docs/why-fast): Presence bits, generated jobs and immediate structural changes. --- # EasyEcs vs DefaultEcs > EasyEcs and DefaultEcs side by side: archetype tables against component pools and entity sets, the same system in both, the tick, and when DefaultEcs fits. URL: https://ecs.xgamedev.net/en/docs/vs-defaultecs Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/vs-defaultecs.md [DefaultEcs](https://github.com/Doraku/DefaultEcs) stores each component type in its own pool and keeps reactive entity sets up to date as components come and go; systems iterate a set's entities and read components through the pools. EasyEcs stores entities with the same components together in archetype tables and generates a struct job per `[ForEach]` method that walks their columns. Both have change tracking, removal tracking, value indexes, parallel systems and saves built in; they differ in storage, in how a system is written and in what a tick costs. In the 20 head-to-head benchmarks both libraries take part in, EasyEcs is faster in 17, within the measurement error in 3 and slower in 0. On the same server tick of 100,000 entities, DefaultEcs takes 3.7× the time of EasyEcs and allocates 60.9 KB per tick, where EasyEcs allocates 0 B. DefaultEcs runs on netstandard1.1-2.1 and Unity; EasyEcs needs .NET 10. - Add a component to 100,000 entities by query, then remove it, vs DefaultEcs: **103× faster**, EasyEcs 78.7 μs, DefaultEcs 8.12 ms - Benchmarks EasyEcs is faster in: **17 / 20**, of those both libraries take part in, beyond the measurement error - DefaultEcs's time for the server tick: **3.7×**, relative to EasyEcs, 100,000 entities - DefaultEcs allocates per tick: **60.9 KB**, EasyEcs allocates 0 B BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## At a glance | | EasyEcs | DefaultEcs | | -------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------ | | Storage | archetype tables, presence bits per column | a pool per component type, entity sets | | A system | an `EcsSystem` with generated `[ForEach]` jobs | `AEntitySetSystem` / `AComponentSystem` with `[With]` / `[Without]` attributes | | Changes during a pass | applied at once | applied at once to sets; `useBuffer` copies the set first, or an `EntityCommandRecorder` | | Change tracking | every `ref` write, `[Changed]` | `NotifyChanged()` at each write, `WhenChanged()` sets | | Removal tracking | `[Removed]` | `WhenRemoved()` sets, completed by hand | | Allocation per server tick | none | allocates | | Runtimes | net10.0 | netstandard1.1-2.1; Unity | ## Concepts side by side | Concept | DefaultEcs | EasyEcs | | ------------------------- | -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | | World | `new World(capacity)` | `new World(new WorldOptions { InitialEntityCapacity = n })` | | Component | any struct | a struct implementing `IComponent` | | Create with components | `var e = world.CreateEntity(); e.Set(a); e.Set(b);` | `world.CreateEntity(a, b)` (placed in its final table at once) | | Create many | the same per entity | `world.CreateEntities(span, a, b)`, or `world.EnsureCapacity(n)` before a loop | | Read, write | `e.Get()` (ref), `world.GetComponents()[e]` | `entity.Hp` (a `ref`; `ref readonly` for a tracked component); a `[ForEach]` parameter | | Tag | `e.Set()` | `entity.SetDead()` | | Destroy | `e.Dispose()` | `entity.Destroy()` | | Singleton | `world.Set(value)`, `world.Get()` | `ISingletonComponent`, `world.SetClock(…)`, `world.Clock`, a `ref T` parameter | | System over a set | `[With(typeof(A)), Without(typeof(B))] class S : AEntitySetSystem` | `class S : EcsSystem` with `[ForEach, Without] static void M(ref A a)` | | System over one component | `AComponentSystem` | a `[ForEach]` method taking `ref A` | | Sequence of systems | `new SequentialSystem(systems)` | `world.AddSystem()` in order, or `[UpdateBefore]` / `[UpdateAfter]` | | Parallel systems | `new ParallelSystem(runner, systems)` | `WorldOptions.ParallelSystems` (conflicts from generated access) | | Parallel set system | `AEntitySetSystem` with a `DefaultParallelRunner` | `[ForEach(Parallel = true)]` | | Entity set | `world.GetEntities().With().Without().AsSet()` | a `QueryFilter`, `world.Query(filter)`, `world.Count(filter)` | | Changed since last look | `.WhenChanged()` + `NotifyChanged()` + `Complete()` | `ITrackChanges` + `[Changed]` | | Removed since last look | `.WhenRemoved()` + `Complete()` | `ITrackChanges` + `[Removed]` | | Index by value | `AsMultiMap()`, `AsMap()` | `IIndexed`, `world.Index()` | | Deferred changes | `EntityCommandRecorder`, `Record(e).Set()`, `Execute()` | not needed | | Disable | `e.Disable()`, `e.Disable()` | a tag and `[Without]`, or `entity.DisableHp()` | | Copy to a world | `e.CopyTo(world)` | `entity.Clone()`, `world.MoveEntities(...)`, a `Prefab` | | Save | `BinarySerializer`, `TextSerializer` | `world.Save(writer)` / `world.Load(bytes)` | | Messages | `world.Subscribe`, `world.Publish` | data: a singleton or components later systems read | ## The same task in both The status system of the headline tick: burning units lose health and the fire goes out after a few ticks. The DefaultEcs port removes the component while it iterates, so the system passes `useBuffer: true` and the set is copied before the update (`DefaultEcsSimulation.cs`). **EasyEcs** ```csharp public struct Hp : IComponent { public int Value, Max; } public struct Fire : IComponent { public int Ticks, DamagePerTick; } public class StatusSystem : EcsSystem { [ForEach] static void Burn(Entity entity, ref Fire fire, ref Hp hp) { hp.Value -= fire.DamagePerTick; if (--fire.Ticks <= 0) entity.RemoveFire(); // a bit flip: the row stays } } ``` ```csharp world.AddSystem(); world.Update(); ``` **DefaultEcs** ```csharp [With(typeof(Fire), typeof(Hp))] public sealed class BurnSystem(World world) : AEntitySetSystem(world, true) // useBuffer: true { protected override void Update(Counters c, ReadOnlySpan entities) { var fires = World.GetComponents(); var hps = World.GetComponents(); foreach (ref readonly var e in entities) { ref var fire = ref fires[e]; hps[e].Value -= fire.DamagePerTick; if (--fire.Ticks <= 0) e.Remove(); } } } var systems = new SequentialSystem(new BurnSystem(world) /* , ... */); systems.Update(counters); ``` ## The numbers Every comparison both libraries take part in, sorted by lead (each row links to its section of [the comparison](https://ecs.xgamedev.net/en/docs/comparison)): | What is measured | EasyEcs | DefaultEcs | Its time vs EasyEcs | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -------------------------- | -------------------- | | [Add a component to 100,000 entities by query, then remove it](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 78.7 μs | 8.12 ms | 103× | | [Add and remove a tag in the passes that find them (1,000 of 100,000)](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | 163 μs | 12.9 ms | 79× (within error) | | [Find the 10 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 507 ns | 37.1 μs | 73× | | [Find the 10 of 100,000 entities that lost a component](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | 830 ns | 39.6 μs | 48× | | [Save 10,000 entities and load them back](https://ecs.xgamedev.net/en/docs/comparison#saves) | 146 μs | 4.33 ms, 4.37 MB allocated | 30× | | [Spawn 10,000 entities beside 100,000, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 138 μs | 1.33 ms, 313 KB allocated | 9.7× | | [Add and remove a tag in the passes that find them (10 of 100,000)](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | 78.2 μs | 496 μs | 6.3× | | [Create 100,000 three-component entities in a fresh world in one call (the others' fastest way)](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 2.71 ms, 4.96 MB allocated | 16.9 ms, 19.1 MB allocated | 6.3× | | [The full server tick: nine systems over 100,000 entities](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | 1.68 ms | 6.24 ms, 60.9 KB allocated | 3.7× | | [Put 100 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 41.4 μs | 103 μs | 2.48× | | [Create 100,000 three-component entities one by one in a fresh world, nothing reserved](https://ecs.xgamedev.net/en/docs/comparison#cold-create) | 7.13 ms, 8.97 MB allocated | 16.9 ms, 19.1 MB allocated | 2.38× | | [Find the 1,000 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 38.5 μs | 77.3 μs | 2.01× | | [Count 100 inventories through an index (1 item traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 425 ns | 838 ns | 1.97× | | [The full server tick: nine systems over 10,000 entities](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | 175 μs | 307 μs, 6.15 KB allocated | 1.76× | | [Find the 1,000 of 100,000 entities that lost a component](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | 66.7 μs | 107 μs | 1.61× | | [Put 10,000 of 100,000 entities to sleep, wake the last ones](https://ecs.xgamedev.net/en/docs/comparison#disabling) | 478 μs | 745 μs | 1.56× | | [Count 100 inventories through an index (100 items traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 5.11 μs | 7.87 μs | 1.54× | | [Four independent systems over 100,000 entities, one after another](https://ecs.xgamedev.net/en/docs/comparison#parallel) | 395 μs | 471 μs | 1.19× | | [Steer 100,000 agents on all cores (parallel query)](https://ecs.xgamedev.net/en/docs/comparison#parallel) | 766 μs | 854 μs | 1.11× (within error) | | [Four independent systems over 100,000 entities, in parallel](https://ecs.xgamedev.net/en/docs/comparison#parallel) | 370 μs | 405 μs | 1.09× (within error) | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The headline tick: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. DefaultEcs takes 3.7× the time of EasyEcs on this tick and allocates 60.9 KB per tick. Its reads go through a pool per component type, indexed by the entity, where EasyEcs walks the columns of a table front to back. **Changes** **Replicate the entities written this tick: 10 or 1,000 of 100,000** | Library | Case | Written | Mean | vs EasyEcs | Allocated | | ---------- | ----------- | ------- | ------- | ---------- | --------- | | EasyEcs | Changed | 10 | 507 ns | 1.00× | 0 B | | EasyEcs | Changed | 1000 | 38.5 μs | 1.00× | 0 B | | DefaultEcs | WhenChanged | 10 | 37.1 μs | 73× | 0 B | | DefaultEcs | WhenChanged | 1000 | 77.3 μs | 2.01× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Removals** **Send the buffs that expired: 10 or 1,000 of 100,000** | Library | Case | Removed | Mean | vs EasyEcs | Allocated | | ---------- | ----------- | ------- | ------- | ---------- | --------- | | EasyEcs | Removed | 10 | 830 ns | 1.00× | 0 B | | EasyEcs | Removed | 1000 | 66.7 μs | 1.00× | 0 B | | DefaultEcs | WhenRemoved | 10 | 39.6 μs | 48× | 0 B | | DefaultEcs | WhenRemoved | 1000 | 107 μs | 1.61× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Indexes** **Trades, then 100 inventories counted** | Library | Case | Trades | Mean | vs EasyEcs | Allocated | | ---------- | -------- | ------ | ------- | ---------- | --------- | | EasyEcs | Index | 1 | 425 ns | 1.00× | 0 B | | EasyEcs | Index | 100 | 5.11 μs | 1.00× | 0 B | | DefaultEcs | MultiMap | 1 | 838 ns | 1.97× | 0 B | | DefaultEcs | MultiMap | 100 | 7.87 μs | 1.54× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Four independent systems over 100,000 entities, sequential and parallel** | Library | Parallel | Mean | vs EasyEcs | Allocated | | ---------- | -------- | ------ | ---------- | --------- | | EasyEcs | False | 395 μs | 1.00× | 0 B | | DefaultEcs | False | 471 μs | 1.19× | 0 B | | EasyEcs | True | 370 μs | 1.00× | 0 B | | DefaultEcs | True | 405 μs | 1.09× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Units fall asleep and wake up, then the awake are summed** | Library | Case | Switched | Mean | vs EasyEcs | Allocated | | ---------- | ------- | -------- | ------- | ---------- | --------- | | EasyEcs | Tag | 100 | 42.4 μs | 1.00× | 0 B | | EasyEcs | Tag | 10000 | 478 μs | 1.00× | 0 B | | DefaultEcs | Disable | 100 | 103 μs | 2.42× | 0 B | | DefaultEcs | Disable | 10000 | 745 μs | 1.56× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Mark the dead and revive them during two passes over 100,000 units** | Library | Case | Killed | Mean | vs EasyEcs | Allocated | | ---------- | --------------- | ------ | ------- | ---------- | --------- | | EasyEcs | Direct | 10 | 78.2 μs | 1.00× | 0 B | | EasyEcs | Direct | 1000 | 163 μs | 1.00× | 0 B | | DefaultEcs | CommandRecorder | 10 | 496 μs | 6.3× | 0 B | | DefaultEcs | CommandRecorder | 1000 | 12.9 ms | 79× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Spawn 10,000 shots, then clear them** | Library | Case | Mean | vs EasyEcs | Allocated | | ---------- | ------------------- | ------- | ---------- | --------- | | EasyEcs | CreateAndDestroyAll | 138 μs | 1.00× | 0 B | | DefaultEcs | PerEntity | 1.33 ms | 9.7× | 313 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Save and load 10,000 units** | Library | Case | Mean | vs EasyEcs | Allocated | | ---------- | -------- | ------- | ---------- | --------- | | EasyEcs | SaveLoad | 146 μs | 1.00× | 0 B | | DefaultEcs | Binary | 4.33 ms | 30× | 4.37 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The DefaultEcs row of the structural-change benchmark at 1,000 kills carries an error as large as its mean in this run, and the parallel rows carry a large error too. ## What DefaultEcs does better - **Reach.** netstandard1.1 to 2.1 and Unity; EasyEcs needs .NET 10. - **Shared components.** `SetSameAs` lets entities share one component value; EasyEcs has no shared components ([D14](https://ecs.xgamedev.net/en/docs/decisions)): keep the shared data in a singleton and an id into it. - **Messages.** A built-in publish / subscribe channel; EasyEcs models messages as data. - **A text serializer** next to the binary one. - **Sparse storage** suits worlds where entities change their component set constantly and are rarely iterated as a whole: adding a component never copies the others. ## When to choose DefaultEcs Choose DefaultEcs when you need old runtimes or Unity, reactive sets or messaging as the way systems talk, and the world is small enough that per-tick allocations and pool lookups do not matter. Choose EasyEcs for a .NET 10 server that iterates many entities every tick, wants change tracking without a `NotifyChanged` at every write, and must not allocate per tick. Porting a DefaultEcs codebase: [Migrate from DefaultEcs](https://ecs.xgamedev.net/en/docs/migrate-from-defaultecs). ## Related - [Migrate from DefaultEcs](https://ecs.xgamedev.net/en/docs/migrate-from-defaultecs): The API mapping and a whole simulation ported, step by step. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): Every benchmark against DefaultEcs, Friflo.Engine.ECS and Arch. - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): How a system is written in EasyEcs. --- # EasyEcs for Unity Entities developers > Coming from Unity Entities (DOTS)? How IComponentData, ISystem, EntityQuery, EntityCommandBuffer, DynamicBuffer and change filters map to EasyEcs on .NET 10. URL: https://ecs.xgamedev.net/en/docs/vs-unity-entities Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/vs-unity-entities.md If you write Unity Entities (DOTS) on the client, EasyEcs will feel familiar on the server: components are structs, systems run over queries, entities live in archetype tables, and there are dynamic buffers, cleanup components, singletons and system groups. EasyEcs is not a Unity package. It is a .NET 10 library for servers and simulations, with no Burst, no baking and no editor, and it trades the job system's command buffers for structural changes that apply immediately. This page maps the concepts; it has no benchmarks against Unity, because none exist. ## What carries over and what does not > **Carries over** > > Struct components and tags, archetype storage, queries with all / none / any filters, singletons, dynamic buffers, > cleanup components, system groups with before / after ordering, prefabs instantiated in bulk, change filters. > **Does not** > > Unity itself: EasyEcs targets net10.0 and does not run in the Unity player or editor. No Burst (the .NET JIT > compiles your systems), no authoring or baking, no transforms or rendering, no `EntityCommandBuffer`. ## Concepts side by side | Unity Entities | EasyEcs | Notes | | ------------------------------------------------------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `World`, `EntityManager` | `World` | One object: entities, components, singletons and systems. One owner thread per world. | | `Entity` (index, version) | `Entity` handle; `EntityId` (index, version) to store in data | A component stores an `EntityId`, not an `Entity` ([EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017)). | | `IComponentData` struct | `IComponent` struct | Unmanaged columns are pinned and 64-byte aligned. | | Empty `IComponentData` (tag) | Empty `IComponent` struct | Adding or removing a tag flips a presence bit after the first time. | | `ISharedComponentData` (chunks split by value) | `IGroup` + `world.GroupBy()` | A table per group value; `QueryFilter.InGroup(value)` walks one. | | `IBufferElementData` + `DynamicBuffer` | `DynamicBuffer` | A list per entity, held as a component; writes are tracked. | | `IEnableableComponent`, `SetComponentEnabled` | `entity.Disable()` / `Enable()` | The value stays and queries skip it; no row moves after the first time. | | `ICleanupComponentData` | `ICleanupComponent` + the `Destroyed` tag | A destroyed entity keeps its cleanup components until a system removes them. | | `SystemAPI.GetSingleton()` | `ISingletonComponent`, a `ref T` parameter of a `[ForEach]` method | Per-world singletons, no entity needed. | | `ISystem` / `SystemBase` with `OnCreate` / `OnUpdate` / `OnDestroy` | `EcsSystem` with `OnCreate` / `OnUpdate` / `OnDestroy` | Systems are stateless: state goes into components or singletons ([EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007)). | | `SystemAPI.Query, RefRO>()` | a `[ForEach]` method taking `ref A`, `in B` | The generator writes the job; `ref` is a write, `in` a read. | | `IJobEntity` | a `[ForEach]` method (a generated struct job) | | | `ScheduleParallel` | `[ForEach(Parallel = true)]` | Chunks of rows on the thread pool; the analyzer rejects methods that would race ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010)). | | `EntityQuery` with `WithAll` / `WithNone` / `WithAny` | `[With]`, `[Without]`, `[WithAny]`; `QueryFilter` for ad-hoc calls | | | Change filter (`WithChangeFilter`) | `ITrackChanges` + `[Changed]` | Per row, not per chunk, and opt-in per component type. | | Structural change events | `[Removed]` | The entities that lost a tracked component since the system last ran. | | `EntityCommandBuffer` | none | `entity.Set`, `Remove`, `Destroy` apply at once, also mid-pass. | | `ComponentSystemGroup`, `[UpdateInGroup]` | `ISystemGroup`, `[UpdateInGroup]`, `world.Update()` | | | `[UpdateBefore]` / `[UpdateAfter]` | `[UpdateBefore]` / `[UpdateAfter]` | A cycle is a build error ([EECS019](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs019)). | | `RateManager`, fixed-step groups | `UpdateInterval`, a group updated when you choose | | | Prefab entity, `EntityManager.Instantiate(prefab, array)` | `Prefab`, `world.Instantiate(prefab, span)` | A `Prefab` lives outside every world; no baking step builds it. | | Baking, authoring components | none | Build entities in code, from a prefab or from a save. | | `LinkedEntityGroup` (destroyed together) | `ChildOf(parent)`, cascading destroy | `world.Children(parent)` lists the children. | | Burst | the .NET JIT, Native AOT | Struct jobs are specialized and inlined per job type. | ## The same system A movement system written both ways. Unity reads the frame time from `SystemAPI.Time`; on a server the tick length is data, a singleton. **EasyEcs** ```csharp public record struct Speed(float Value) : IComponent; public record struct TickLength(float Seconds) : ISingletonComponent; public class MoveSystem : EcsSystem { [ForEach, Without] static void Move(ref Position position, in Speed speed, in TickLength tick) => position = position with { Y = position.Y + speed.Value * tick.Seconds }; } ``` ```csharp world.SetTickLength(0.05f); // generated: adds the singleton world.AddSystem(); world.CreateEntity(new Position(0, 0), new Speed(2)); world.Update(); ``` **Unity Entities** ```csharp public struct Speed : IComponentData { public float Value; } public partial struct MoveSystem : ISystem { public void OnUpdate(ref SystemState state) { float dt = SystemAPI.Time.DeltaTime; foreach (var (transform, speed) in SystemAPI.Query, RefRO>().WithNone()) transform.ValueRW.Position.y += speed.ValueRO.Value * dt; } } ``` ## Structural changes without a command buffer In Unity, structural changes during iteration or inside a job go through an `EntityCommandBuffer` that plays back at a sync point. In EasyEcs a system changes structure where it decides to, and the change is visible to every later system in the same update: ```csharp public class DeathSystem : EcsSystem { [ForEach, Without] static void Die(Entity unit, in Health health) { if (health.Value <= 0) unit.SetDead(); // no command buffer, no sync point } } ``` The pass stays safe: a row that loses its entity mid-pass becomes a tombstone until the pass ends, and every entity is visited at most once. What you give up is structural changes from parallel code: a `[ForEach(Parallel = true)]` method cannot change structure, and the analyzer says so. ## Change filters are per row Unity's change filter works per chunk: a chunk counts as changed when any system had write access to it, so a filter returns whole chunks, written or not. EasyEcs tracks per row, opt-in per component: mark the component `ITrackChanges` and `[Changed]` visits only the rows written through a `ref` since the system last ran, skipping unwritten tables, 4,096-row blocks and 64-row words. `[Removed]` does the same for the entities that lost the component. See [change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking). ## Is EasyEcs a Unity ECS? No. EasyEcs targets net10.0 only and does not run in Unity. A common setup is Unity Entities (or any engine) on the client and EasyEcs on the server, sharing plain message types: the concepts above transfer, the code does not. For an ECS that runs inside Unity, use Unity Entities, or one of the libraries in [the comparison](https://ecs.xgamedev.net/en/docs/comparison) that target netstandard2.1. ## Related - [What is an ECS?](https://ecs.xgamedev.net/en/docs/what-is-ecs): Entities, components, systems and archetype storage. - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): A first world, components and systems in a few minutes. - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): Methods, filters, ordering, groups and parallel methods. --- # Migrate from Friflo.Engine.ECS > Port a Friflo.Engine.ECS codebase to EasyEcs: concepts and API mapped old to new, chunk loops and command buffers turned into [ForEach] methods, pitfalls. URL: https://ecs.xgamedev.net/en/docs/migrate-from-friflo Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/migrate-from-friflo.md Friflo.Engine.ECS and EasyEcs are both archetype libraries that allocate nothing per tick, so the data model ports one to one: components stay structs, tags stay empty structs, an `EntityStore` becomes a `World`. What changes is how a system is written. A cached `ArchetypeQuery` iterated chunk by chunk becomes a `[ForEach]` method whose parameters are the components; changes recorded in a `CommandBuffer` become direct calls; `OnComponentRemoved` subscriptions become `[Removed]` methods. The worked example is the real port in the repository: [`FrifloSimulation.cs`](https://github.com/JasonXuDeveloper/EasyEcs/blob/master/benchmarks/EasyEcs.Comparison/FrifloSimulation.cs) and the EasyEcs world it was ported from, [`WorldSimulation.cs`](https://github.com/JasonXuDeveloper/EasyEcs/blob/master/benchmarks/EasyEcs.Benchmark/WorldSimulation.cs). ## Before you start > **Requirements** > > EasyEcs targets net10.0 only. Code that must also run in Unity or on netstandard2.1 / .NET 6-8 stays on Friflo. ```bash dotnet add package EasyEcs ``` Both libraries name their component interface `IComponent`. During a port, alias one of them (`using F = Friflo.Engine.ECS;`), as the comparison project does. ## Concepts | Friflo.Engine.ECS | EasyEcs | What changes | | ------------------------------------------------ | --------------------------------------------------- | --------------------------------------------------------------------------------------------------- | | `EntityStore` | `World` | One owner thread per world. | | `IComponent` struct | `IComponent` struct | Nothing but the namespace. | | `ITag` | An empty `IComponent` struct | Tags are components; removing one flips a bit. | | `ArchetypeQuery` + `Chunks` loops | A `[ForEach]` method in an `EcsSystem` | The generator writes the loop. | | `CommandBuffer` + `Playback()` | Direct calls | Changes apply at once, also mid-pass. | | `UniqueEntity` | `ISingletonComponent` | Per-world data, a `ref` parameter. | | `SystemRoot`, `SystemGroup`, `QuerySystem` | `World.AddSystem()`, `ISystemGroup`, `EcsSystem` | | | `OnComponentRemoved` / `OnComponentAdded` events | `[Removed]`, `[Changed]` | State changes are data. | | `entity.Enabled` | A tag and `[Without]`, or `entity.Disable()` | EasyEcs disables components, not whole entities ([D8](https://ecs.xgamedev.net/en/docs/decisions)). | ## API mapping The rows name the components of the example below (`Health`, the tag `Dead`). For each component the generator writes named members (`entity.Health`, `HasHealth`, `SetHealth(…)`, `IsDead`): use them in your code. The generic calls after them (`Get()`, `Set(c)`, `Remove()`) are for generic code ([generated members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members)). ### Entities and components | Friflo.Engine.ECS | EasyEcs | | ----------------------------------------------- | ------------------------------------------------------------- | | `var store = new EntityStore();` | `var world = new World();` | | `store.EnsureCapacity(n)` | `world.EnsureEntityCapacity(n)` | | `archetype.EnsureCapacity(n)` | `world.EnsureCapacity(n)` (the entity storage too) | | `store.CreateEntity(a, b, c)` | `world.CreateEntity(a, b, c)` | | `store.Count` | `world.EntityCount` | | `entity.AddComponent(c)` | `entity.SetHealth(100, 100)`, `entity.Set(c)` | | `entity.RemoveComponent()` | `entity.RemoveHealth()`, `entity.Remove()` | | `ref var c = ref entity.GetComponent()` | `ref var hp = ref entity.Health`, `entity.Get()` | | `entity.HasComponent()` | `entity.HasHealth`, `entity.Has()` | | `entity.AddTag()` / `RemoveTag()` | `entity.SetDead()` / `entity.RemoveDead()` | | `entity.Tags.Has()` | `entity.IsDead` | | `entity.DeleteEntity()` | `entity.Destroy()` | | `store.GetEntityById(id)` | `world.TryGetEntity(entityId, out var entity)` | | `store.CloneEntity(template)` | `world.Instantiate(prefab)`, `entity.Clone()` | ### Queries and iteration | Friflo.Engine.ECS | EasyEcs | | ----------------------------------------------------- | ------------------------------------------------------------------------------------ | | `store.Query()` | the method's parameters: `static void M(ref A a, in B b)` | | `.AllComponents(ComponentTypes.Get())` | `[With]` | | `.WithoutAnyComponents(ComponentTypes.Get())` | `[Without]` | | `.AllTags(Tags.Get())` / `.WithoutAnyTags(...)` | `[With]` / `[Without]` | | `foreach (var (as, bs, entities) in query.Chunks)` | a batch method `static void M(Span a, ReadOnlySpan b)`, or a per-entity method | | `entities.Ids[i]`, `entities.EntityAt(i)` | an `Entity` parameter, or an `EntitySpan` in a batch method | | `query.ForEachEntity((ref A a, Entity e) => ...)` | `static void M(Entity e, ref A a)` | | `query.Count` | `world.Count(filter)` | | `query.ForEach(...)` + `RunParallel()` | `[ForEach(Parallel = true)]` | ### Changes, events and features | Friflo.Engine.ECS | EasyEcs | | ----------------------------------------------------------- | -------------------------------------------------------------- | | `buffer.AddComponent(id, c)` + `Playback()` | `entity.Set(c)` | | `buffer.RemoveComponent(id)`, `RemoveTag(id)` | `entity.Remove()` | | `buffer.DeleteEntity(id)` | `entity.Destroy()` | | `buffer.CreateEntity()` + `AddComponent` per component | `world.CreateEntity(a, b, c)` | | `EntityBatch` + `query.Entities.ApplyBatch(batch)` | `world.SetAll(value, filter)`, `world.RemoveAll(filter)` | | `store.OnComponentRemoved += ...` | `[ForEach, Removed]` (with `T : ITrackChanges`) | | A dirty tag added on write | `T : ITrackChanges` + `[ForEach, Changed]` | | `IIndexedComponent`, `store.ComponentIndex()[key]` | `IIndexed`, `world.Index().Find(key)` | | `query.ValueInRange(min, max)` | `world.Index().Range(min, max)` | | `ILinkComponent`, `GetIncomingLinks()` | an `EntityId` key: `IIndexed`, `index.Find(target)` | | `ILinkRelation`, `AddRelation`, `GetRelations()` | `IRelation`, `entity.AddRelation(...)`, `world.Relations()` | | `AddChild`, `ChildEntities` | `ChildOf(parent)`, `world.Children(parent)` | | `EntitySerializer` (JSON) | `world.Save(writer)` / `world.Load(bytes)` (binary) | ## A worked example: the headline simulation ### Components and tags The structs keep their fields. `Dead : ITag` becomes an empty component; the counters become a singleton. ```csharp public struct Position : IComponent { public float X, Y; } public struct Velocity : IComponent { public float X, Y; } public struct Health : IComponent { public int Value, Max; } public struct AoiCell : IComponent { public int Cell; } public struct Player : IComponent { public long AccountId; } public struct Npc : IComponent { public int TemplateId; } public struct Dead : IComponent; public struct WorldStats : ISingletonComponent { public int CellChanges, Deaths, NpcKills; } ``` ### A chunk loop becomes a method Friflo: ```csharp _cells = _store.Query().WithoutAnyTags(Tags.Get()); foreach (var (positions, cells, _) in _cells.Chunks) { var ps = positions.Span; var cs = cells.Span; for (int i = 0; i < ps.Length; i++) { int cell = Rules.Cell(ps[i].X, ps[i].Y); if (cell == cs[i].Cell) continue; cs[i].Cell = cell; _c.CellChanges++; } } ``` EasyEcs: one method per row; the counters are a `ref` singleton parameter, resolved once per pass. ```csharp public class AoiSystem : EcsSystem { [ForEach, Without] static void UpdateCell(in Position p, ref AoiCell aoi, ref WorldStats stats) { int cell = (int)(p.Y * (1f / 64f)) * 64 + (int)(p.X * (1f / 64f)); if (cell == aoi.Cell) return; aoi.Cell = cell; stats.CellChanges++; } } ``` ### The command buffer goes Friflo records the tag and plays the buffer back after the loop: ```csharp foreach (var (healths, entities) in _alive.Chunks) { var health = healths.Span; for (int i = 0; i < health.Length; i++) { if (health[i].Value > 0) continue; _buffer.AddTag(entities.Ids[i]); _c.Deaths++; if (entities.EntityAt(i).HasComponent()) _c.NpcKills++; } } _buffer.Playback(); ``` EasyEcs adds it where it is decided, and the respawn system after it already sees the dead: ```csharp public class DeathSystem : EcsSystem { [ForEach, Without] static void CheckDeath(Entity entity, in Health health, ref WorldStats stats) { if (health.Value > 0) return; entity.SetDead(); stats.Deaths++; if (entity.HasNpc) stats.NpcKills++; } } public class RespawnSystem : EcsSystem { [ForEach, With, With] static void Respawn(Entity entity, ref Health health) { health.Value = health.Max; entity.RemoveDead(); } } ``` ### Clones become prefabs Friflo spawns NPCs by cloning a template entity of the store, which queries see like any other. A `Prefab` lives outside every world, and a wave is one call: ```csharp private static readonly Prefab Grunt = new Prefab() .SetPosition(0, 0).SetVelocity(0, 0).SetHealth(value: 100, max: 100) .SetAoiCell(cell: -1).SetNpc(templateId: 7); ``` ```csharp var wave = new Entity[5_000]; world.Instantiate(Grunt, wave); ``` ### An event becomes a `[Removed]` method A subscription that collects the entities which lost a component, read once per tick, becomes a method. The component must be tracked: ```csharp public record struct Buff(int Ticks) : IComponent, ITrackChanges; public record struct Expired(int Count) : IComponent; public class BuffReplication : EcsSystem { [ForEach, Removed] static void Send(ref Expired expired) => expired.Count++; } ``` ### The tick Friflo's `Tick()` calls every loop and every playback in order. EasyEcs runs the systems in the order they were added: ```csharp world.AddSingleton(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.Update(); ``` The two versions of the whole tick, on the same machine: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Pitfalls | Mistake | What happens | Caught by | | -------------------------------------------------------------------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------- | | Both `IComponent`s imported | Ambiguous references | Compiler error: alias one namespace | | Keeping a `[Removed]` component untracked | Removals are not recorded | Add `ITrackChanges` to `T` | | Taking `T` as a parameter of a `[Removed]` method | No row can both have and lack `T` | [EECS016](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs016) | | Storing an `Entity` in a component (Friflo's link components do) | The column holds references | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) (warning): store `EntityId` | | Writing an indexed component through `ref` (Friflo re-indexes on `AddComponent`) | The index cannot see the new key | [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015): use `Set` | | Expecting `Enabled = false` on a whole entity | No such switch | Use a tag and `[Without]` | | A static method without `Entity` or `World` that adds a tag | It promised no structural change | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | ## Related - [EasyEcs vs Friflo.Engine.ECS](https://ecs.xgamedev.net/en/docs/vs-friflo): The two libraries side by side, with every benchmark. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): `[Changed]` and `[Removed]` instead of dirty tags and events. - [Prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs): Templates outside every world, instantiated one at a time or as a wave. --- # Migrate from Arch > Port an Arch ECS codebase to EasyEcs step by step: concepts and API mapped old to new, a server simulation ported from the benchmarks, and the pitfalls. URL: https://ecs.xgamedev.net/en/docs/migrate-from-arch Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/migrate-from-arch.md Arch and EasyEcs share the archetype model, so most of a port is mechanical: a `QueryDescription` becomes filter attributes, a struct job's `Update` becomes a `[ForEach]` method, and `world.Add` / `Remove` / `Destroy` on an entity become calls on its handle. The one change of habit is the command buffer: EasyEcs has none, because structural changes apply at once, also in the middle of a query. The worked example below is the real port in the repository: [`ArchSimulation.cs`](https://github.com/JasonXuDeveloper/EasyEcs/blob/master/benchmarks/EasyEcs.Comparison/ArchSimulation.cs) and the EasyEcs world it was ported from, [`WorldSimulation.cs`](https://github.com/JasonXuDeveloper/EasyEcs/blob/master/benchmarks/EasyEcs.Benchmark/WorldSimulation.cs), checked by the comparison project to produce the same counters. ## Before you start > **Requirements** > > EasyEcs targets net10.0 only. A project that must also build for Unity, netstandard2.1 or .NET 8 cannot move its > ECS code to EasyEcs. ```bash dotnet add package EasyEcs ``` The package carries the source generator and the analyzer: `[ForEach]` systems, the generated members (`entity.Position`, `world.Clock`) and the EECS rules work with nothing else to install. ## Concepts | Arch | EasyEcs | What changes | | -------------------------------- | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `World.Create()` | `new World(options)` | A world has one owner thread; run one world per thread. | | Any struct is a component | A struct implementing `IComponent` | Add the interface; the analyzer rejects classes ([EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006)). | | `QueryDescription` | Filter attributes on a `[ForEach]` method, or a `QueryFilter` | Written once, on the method; the generator keeps the filter in a static field. | | `IForEach` + `InlineQuery` | A `[ForEach]` method in an `EcsSystem` | The generator writes the struct job and the call. | | `CommandBuffer` + `Playback` | Direct calls | Changes apply at once; later systems see them. | | A counters object passed to jobs | A singleton (`ISingletonComponent`) | Taken as a `ref` parameter, resolved once per pass. | | Arch.Extended systems | `EcsSystem`, `ISystemGroup`, `[UpdateBefore]` / `[UpdateAfter]` | Built in. | | Events | `[Changed]`, `[Removed]`, tags queried later | State changes are data. | ## API mapping The rows name the components of the example below (`Health`, the tag `Dead`). For each component the generator writes named members (`entity.Health`, `HasHealth`, `SetHealth(…)`, `IsDead`): use them in your code. The generic calls after them (`Get()`, `Set(c)`, `Remove()`) are for generic code ([generated members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members)). ### World and entities | Arch | EasyEcs | | ------------------------------------------- | ------------------------------------------------------------------------ | | `var world = World.Create();` | `var world = new World(new WorldOptions { InitialEntityCapacity = n });` | | `World.Destroy(world);` | `world.Dispose();` | | `world.Create(a, b, c)` | `world.CreateEntity(a, b, c)` | | `world.Destroy(entity)` | `entity.Destroy()` | | `world.Add(entity, c)` | `entity.SetHealth(100, 100)`, `entity.Set(c)` | | `world.Add(entity)` | `entity.SetDead()` | | `world.Remove(entity)` | `entity.RemoveHealth()`, `entity.Remove()` | | `world.Has(entity)` | `entity.HasHealth`, `entity.IsDead` for a tag, `entity.Has()` | | `ref var c = ref world.Get(entity)` | `ref var hp = ref entity.Health`, `entity.Get()` | | `world.Size` | `world.EntityCount` | | `entity.Id` | `entity.Id.Index`; store `entity.Id` (an `EntityId`) in data | | `world.EnsureCapacity(in signature, n)` | `world.EnsureCapacity(n)`, `world.EnsureCapacity(prefab, n)` | ### Queries and iteration | Arch | EasyEcs | | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | `new QueryDescription().WithAll()` | the method's component parameters: `static void M(ref A a, in B b)` | | `.WithAll()` (a tag the job does not read) | `[With]` | | `.WithNone()` | `[Without]` | | `.WithAny()` | `[WithAny, WithAny]` | | `struct J : IForEach` + `world.InlineQuery(in q, ref job)` | `[ForEach]` method; outside systems `world.ForEach(ref job, in filter)` with `IForEach.Execute` | | `IForEachWithEntity` + `InlineEntityQuery` | an `Entity` parameter: `static void M(Entity e, ref A a)` | | Chunk iteration (`GetChunkIterator`, `chunk.GetSpan()`) | a batch method: `static void M(Span a, ReadOnlySpan b)` | | `world.CountEntities(in q)` | `world.Count(filter)` | | `world.InlineParallelQuery(in q, ref job)` | `[ForEach(Parallel = true)]` | ### Structural changes | Arch | EasyEcs | | ------------------------------------------------- | --------------------------------------------------------------------------- | | `buffer.Add(e, c)` then `buffer.Playback(world)` | `e.SetBurning(10, 3)`, `e.Set(c)` | | `buffer.Remove(e)` | `e.RemoveBurning()` | | `buffer.Destroy(e)` | `e.Destroy()` | | `var n = buffer.Create(types); buffer.Set(n, c);` | `world.CreateEntity(a, b, c)` (a `World` parameter in a `[ForEach]` method) | | `world.Add(in q, value)` | `world.SetAll(value, filter)` | | `world.Remove(in q)` | `world.RemoveAll(filter)` | | `world.Destroy(in q)` | `world.DestroyEntities(filter)` | ## A worked example: the headline simulation ### Components Add `IComponent`. A tag stays an empty struct. Counters that Arch kept in an object passed to every job become a singleton. ```csharp public struct Position : IComponent { public float X, Y; } public struct Velocity : IComponent { public float X, Y; } public struct Health : IComponent { public int Value, Max; } public struct Attack : IComponent { public int Damage, Cooldown, Interval; } public struct Lifetime : IComponent { public int Ticks; } public struct Burning : IComponent { public int Ticks, DamagePerTick; } public struct Player : IComponent { public long AccountId; } public struct Npc : IComponent { public int TemplateId; } public struct Projectile : IComponent { public int OwnerId; } public struct Stunned : IComponent { public int Ticks; } public struct Dead : IComponent; public struct WorldStats : ISingletonComponent { public long Tick; public int Hits, Deaths, NpcKills, Spawns; } ``` ### A query and its job become one method Arch: ```csharp private static readonly QueryDescription Moving = new QueryDescription().WithAll().WithNone(); private struct Move : IForEach { public void Update(ref Position p, ref Velocity v) { /* ... */ } } var move = new Move(); world.InlineQuery(in Moving, ref move); ``` EasyEcs: the filter goes on the method, the parameters are the components. ```csharp public class MovementSystem : EcsSystem { [ForEach, Without, Without] static void Move(ref Position p, ref Velocity v) { p.X += v.X; p.Y += v.Y; if (p.X < 0 || p.X > 4096) v.X = -v.X; if (p.Y < 0 || p.Y > 4096) v.Y = -v.Y; } } ``` ### The command buffer goes Arch records the status change and plays it back after the query: ```csharp public void Update(Entity e, ref Attack attack, ref Health health) { if (--attack.Cooldown > 0) return; attack.Cooldown = attack.Interval; C.Hits++; health.Value -= attack.Damage; if (Rng.Chance(C.Tick, e.Id, 1, 50) && !W.Has(e)) B.Add(e, new Burning { Ticks = 10, DamagePerTick = 3 }); } // ... _buffer.Playback(_world); ``` EasyEcs applies it on the spot. The counters are a `ref` singleton parameter. ```csharp public class CombatSystem : EcsSystem { [ForEach, Without, Without] static void Fight(Entity entity, ref Attack attack, ref Health health, ref WorldStats stats) { if (--attack.Cooldown > 0) return; attack.Cooldown = attack.Interval; stats.Hits++; health.Value -= attack.Damage; if (entity.Id.Index % 20 == 0 && !entity.HasBurning) entity.SetBurning(ticks: 10, damagePerTick: 3); } } public class StatusSystem : EcsSystem { [ForEach] static void Burn(Entity entity, ref Burning burning, ref Health health) { health.Value -= burning.DamagePerTick; if (--burning.Ticks <= 0) entity.RemoveBurning(); } } public class DeathSystem : EcsSystem { [ForEach, Without] static void CheckDeath(Entity entity, in Health health, ref WorldStats stats) { if (health.Value > 0) return; entity.SetDead(); stats.Deaths++; if (entity.HasNpc) stats.NpcKills++; } } ``` ### Creating and destroying Arch creates projectiles through the buffer with a signature and one `Set` per component. EasyEcs creates the entity with its components in one call, placed in its final table; a method that creates or destroys takes `World` or `Entity`. ```csharp public class ShootingSystem : EcsSystem { [ForEach, With, Without] static void Shoot(Entity shooter, in Position p, in Velocity v, ref WorldStats stats, World world) { if ((stats.Tick + shooter.Id.Index) % 20 != 0) return; stats.Spawns++; world.CreateEntity(p, new Velocity { X = v.X * 4, Y = v.Y * 4 }, new Lifetime { Ticks = 20 }, new Projectile { OwnerId = shooter.Id.Index }); } } public class LifetimeSystem : EcsSystem { [ForEach] static void Expire(Entity entity, ref Lifetime lifetime) { if (--lifetime.Ticks <= 0) entity.Destroy(); } } public sealed class ClockSystem : EcsSystem { protected override void OnUpdate() => World.WorldStats.Tick++; } ``` ### The tick Arch's `Tick()` calls every query and every playback in order. EasyEcs runs the systems in the order they were added (or as `[UpdateBefore]` / `[UpdateAfter]` say) with one call. ```csharp using var sim = new World(new WorldOptions { InitialEntityCapacity = 200_000 }); sim.AddSingleton(); sim.AddSystem(); sim.AddSystem(); sim.AddSystem(); sim.AddSystem(); sim.AddSystem(); sim.AddSystem(); sim.AddSystem(); sim.EnsureCapacity(100_000); for (int i = 0; i < 100_000; i++) sim.CreateEntity(new Position { X = i % 4096, Y = i / 25 }, new Velocity { X = 1, Y = -1 }, new Health { Value = 150, Max = 150 }, new Attack { Damage = 5, Cooldown = i % 10, Interval = 8 }, new Player { AccountId = i }); sim.Update(); // one tick ``` The whole port, with the area-of-interest grid and respawns, is the pair of files linked at the top. On the same machine the EasyEcs version runs the tick in 1.68 ms against 5.76 ms for Arch, at 100,000 entities: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Pitfalls | Mistake | What happens | Caught by | | ----------------------------------------------------------------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------- | | Keeping a component as a plain struct without `IComponent` | It cannot be a parameter or a column | Compiler error: the constraint `IComponent` | | A class as a component | Rejected | [EECS006](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs006) | | Porting the counters object as a field of the system | Systems are stateless | [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007): use a singleton | | Storing an `Entity` in a component (Arch's `Entity` was a plain struct) | The column holds references | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) (warning): store `EntityId` | | A static method without `Entity` or `World` that adds a component | It promised no structural change | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013): take the `Entity` | | Keeping a "pending changes" list to apply after the loop | Works, but costs a second pass | Code review: apply the change where it is decided | | A parallel method that changes structure or writes a singleton | Data races | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) | ## Related - [EasyEcs vs Arch](https://ecs.xgamedev.net/en/docs/vs-arch): The two libraries side by side, with every benchmark. - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): Parameters, filters, ordering, groups and parallel methods. - [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes): What applies at once during a pass, and why it is safe. --- # Migrate from DefaultEcs > Port a DefaultEcs codebase to EasyEcs: entity sets, AEntitySetSystem, WhenChanged and EntityMultiMap mapped old to new, a ported simulation and pitfalls. URL: https://ecs.xgamedev.net/en/docs/migrate-from-defaultecs Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/migrate-from-defaultecs.md DefaultEcs keeps each component in its own pool and lets systems iterate entity sets; EasyEcs keeps entities with the same components together in tables and runs generated jobs over them. The port is mostly a change of shape: an `AEntitySetSystem` with `[With]` / `[Without]` attributes and a `World.GetComponents()` loop becomes an `EcsSystem` with one `[ForEach]` method whose parameters are the components; an entity built with one `Set` per component is created with all of them at once; `WhenChanged()` sets fed by `NotifyChanged()` become `[Changed]` methods with nothing to notify. The worked example is the real port in the repository: [`DefaultEcsSimulation.cs`](https://github.com/JasonXuDeveloper/EasyEcs/blob/master/benchmarks/EasyEcs.Comparison/DefaultEcsSimulation.cs) and the EasyEcs world it was ported from, [`WorldSimulation.cs`](https://github.com/JasonXuDeveloper/EasyEcs/blob/master/benchmarks/EasyEcs.Benchmark/WorldSimulation.cs). ## Before you start > **Requirements** > > EasyEcs targets net10.0 only. Code that must run in Unity or on netstandard stays on DefaultEcs. ```bash dotnet add package EasyEcs ``` ## Concepts | DefaultEcs | EasyEcs | What changes | | ----------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------ | | `World` | `World` | One owner thread per world. | | Any struct is a component | A struct implementing `IComponent` | Add the interface. | | A pool per component type | Archetype tables | An entity's components sit in one row; gaining a new one copies the row. | | `EntitySet` (`GetEntities().With().AsSet()`) | Filters on a `[ForEach]` method, or a `QueryFilter` | No set to keep or dispose. | | `AEntitySetSystem`, `AComponentSystem` | `EcsSystem` with `[ForEach]` methods | The generator writes the loop and the component access. | | `SequentialSystem`, `ParallelSystem` | `world.AddSystem()`, `WorldOptions.ParallelSystems` | Order by registration or `[UpdateBefore]` / `[UpdateAfter]`. | | `World.Set()` / `Get()` | `ISingletonComponent` | A `ref` parameter of a `[ForEach]` method. | | `NotifyChanged()` + `WhenChanged()` | `ITrackChanges` + `[Changed]` | Every `ref` write is the change. | | `WhenRemoved()` | `ITrackChanges` + `[Removed]` | No `Complete()` to call. | | `EntityCommandRecorder` | Direct calls | Changes apply at once. | | `Publish` / `Subscribe` | Data: components or singletons later systems read | No messages. | ## API mapping The rows name the components of the example below (`Hp`, the tag `Dead`). For each component the generator writes named members (`e.Hp`, `HasHp`, `SetHp(…)`, `IsDead`): use them in your code. The generic calls after them (`Get()`, `Set(c)`, `Remove()`) are for generic code ([generated members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members)). ### Entities and components | DefaultEcs | EasyEcs | | --------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `new World(maxCapacity)` (a hard limit) | `new World(new WorldOptions { InitialEntityCapacity = n })` (a starting size; the world grows) | | `var e = world.CreateEntity(); e.Set(a); e.Set(b);` | `var e = world.CreateEntity(a, b);` | | `e.Set(c)` (add or replace) | `e.SetHp(100)`, `e.Set(c)` | | `e.Set()` | `e.SetDead()` | | `ref var c = ref e.Get()` | `e.Hp` to read, `ref var hp = ref e.WriteHp()` to write | | `e.Has()` | `e.HasHp`, `e.Has()` | | `e.Remove()` | `e.RemoveHp()`, `e.Remove()` | | `e.Dispose()` | `e.Destroy()` | | `e.Disable()` / `Enable()` | a tag (`Asleep`) and `[Without]` | | `e.Disable()` / `Enable()` | `e.DisableHp()` / `EnableHp()` | | `e.CopyTo(world)` | `e.Clone()`; `world.MoveEntities(...)` for another world; a `Prefab` for templates | | `e.GetHashCode()` as an id | `e.Id` (an `EntityId`: index and version) | | `world.Set(value)` / `world.Get()` | `world.SetWorldStats(…)`, `world.WorldStats` | ### Systems and sets | DefaultEcs | EasyEcs | | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | `[With(typeof(A), typeof(B))]` on an `AEntitySetSystem` | the method's parameters `(ref A a, in B b)`; `[With]` for one it does not read | | `[Without(typeof(C))]` | `[Without]` | | `Update(T state, ReadOnlySpan entities)` + `World.GetComponents()[e]` | `static void M(ref A a)`, or a batch method taking `Span` | | the `useBuffer: true` constructor argument | nothing: structural changes are safe in any pass | | `AComponentSystem.Update(T state, ref A a)` | `[ForEach] static void M(ref A a)` | | `new SequentialSystem(a, b, c)` + `Update(state)` | `world.AddSystem(); ...; world.Update();` | | `new ParallelSystem(runner, systems)` | `new WorldOptions { ParallelSystems = true }` | | `AEntitySetSystem` with a `DefaultParallelRunner` | `[ForEach(Parallel = true)]` | | `GetEntities().With().AsSet().Count` | `world.Count(filter)` | | `GetEntities().AsMultiMap()`, `map.Count(key)` | `IIndexed`, `world.Index().Count(key)` | | `recorder.Record(e).Set()` + `recorder.Execute()` | `e.Set(new T())` | | `BinarySerializer.Serialize(stream, world)` | `world.Save(writer)` | | `BinarySerializer.Deserialize(stream)` | `world.Load(bytes)` | ## A worked example: the headline simulation ### Components Add `IComponent`. The counters that DefaultEcs passed as the systems' state become a singleton. ```csharp public struct Position : IComponent { public float X, Y; } public struct Velocity : IComponent { public float X, Y; } public struct Health : IComponent { public int Value, Max; } public struct Lifetime : IComponent { public int Ticks; } public struct Player : IComponent { public long AccountId; } public struct Projectile : IComponent { public int OwnerId; } public struct Dead : IComponent; public struct WorldStats : ISingletonComponent { public long Tick; public int Spawns; } ``` ### A set system becomes a method DefaultEcs: ```csharp [With(typeof(Position), typeof(Velocity)), Without(typeof(Stunned), typeof(Dead))] public sealed class MovementSystem(World world) : AEntitySetSystem(world, false) { protected override void Update(Counters c, ReadOnlySpan entities) { var positions = World.GetComponents(); var velocities = World.GetComponents(); foreach (ref readonly var e in entities) { ref var p = ref positions[e]; ref var v = ref velocities[e]; p.X += v.X; p.Y += v.Y; } } } ``` EasyEcs: the attributes become filters, the component lookups become parameters. ```csharp public class MovementSystem : EcsSystem { [ForEach, Without, Without] static void Move(ref Position p, in Velocity v) { p.X += v.X; p.Y += v.Y; } } ``` ### Structural changes need no buffer DefaultEcs passes `useBuffer: true` to systems that destroy or create while they iterate. EasyEcs passes are safe as they are: a method that destroys takes the `Entity`, one that creates takes the `World`, and an entity is created with all its components at once. ```csharp public class LifetimeSystem : EcsSystem { [ForEach] static void Expire(Entity entity, ref Lifetime lifetime) { if (--lifetime.Ticks <= 0) entity.Destroy(); } } public class ShootingSystem : EcsSystem { [ForEach, With, Without] static void Shoot(Entity shooter, in Position p, in Velocity v, ref WorldStats stats, World world) { if ((stats.Tick + shooter.Id.Index) % 20 != 0) return; stats.Spawns++; world.CreateEntity(p, new Velocity { X = v.X * 4, Y = v.Y * 4 }, new Lifetime { Ticks = 20 }, new Projectile { OwnerId = shooter.Id.Index }); } } ``` ### `WhenChanged` becomes `[Changed]` DefaultEcs needs a `NotifyChanged()` next to every write and a `Complete()` after reading the set: ```csharp var changed = world.GetEntities().With().WhenChanged().AsSet(); entity.Get().Value--; entity.NotifyChanged(); foreach (ref readonly var e in changed.GetEntities()) replicas[e].Value = hps[e].Value; changed.Complete(); ``` EasyEcs: mark the component tracked; every write through a `ref` is the change. ```csharp public record struct Hp(int Value) : IComponent, ITrackChanges; public record struct Replica(int Value) : IComponent; public class Replication : EcsSystem { [ForEach, Changed] static void Copy(in Hp hp, ref Replica replica) => replica = new Replica(hp.Value); } ``` ### The tick A `SequentialSystem` becomes the world's system list; the state argument becomes the singleton. ```csharp world.AddSingleton(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.AddSystem(); world.Update(); ``` The two versions of the whole tick, on the same machine: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Pitfalls | Mistake | What happens | Caught by | | --------------------------------------------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------- | | Porting the state object as a field of the system | Systems are stateless | [EECS007](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs007): use a singleton | | Taking a component by value in a `[ForEach]` method | A copy: writes are lost | [EECS002](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs002), with a code fix to `ref` / `in` | | Adding components one `Set` at a time on creation | One row copy per component | Code review: `world.CreateEntity(a, b, c)` | | A static method without `Entity` or `World` that destroys | It promised no structural change | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | | Keeping `NotifyChanged` calls | Nothing to call: there is no such method | Compiler error | | Taking a tracked component by `ref` only to read it | Every visited row counts as changed | Code review: declare it `in` | | Using `GetHashCode()` as an entity id | Ids are recycled | Store `entity.Id` (`EntityId`, with its version) | ## Related - [EasyEcs vs DefaultEcs](https://ecs.xgamedev.net/en/docs/vs-defaultecs): The two libraries side by side, with every benchmark. - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): Parameters, filters, ordering, groups and parallel methods. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): `[Changed]` and `[Removed]` instead of reactive sets. --- # API and complexity > Every public type and call of EasyEcs on one page, grouped by task, with its time complexity and allocations. The member reference comes from the XML docs. URL: https://ecs.xgamedev.net/en/docs/api Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/api.md Every public type and call of EasyEcs, grouped by what you do with it, with the cost of each. Everything is in `namespace EasyEcs`. T1..T9 overloads come from one template each ([Architecture](https://ecs.xgamedev.net/en/docs/architecture#source-generators-and-analyzer-easyecsgenerator)). For signatures, parameters and the XML documentation of each member, see the generated [API reference](https://ecs.xgamedev.net/en/docs/reference); its pages quote the complexities below. Notation: - *n*: components in the call (1 to 9). - *c*: components of the entity. - *M*: tables (archetypes) matching a query. - *S*: rows of those tables: living entities, plus tombstones while a pass that makes structural changes runs. - *k*: entities of one key of an index; *L*: links of one entity. - "Amortized": tables and the entity array occasionally double. Unless a row says otherwise, a call allocates nothing once the world is warmed up, and only the world's owner thread may make it ([Threading](https://ecs.xgamedev.net/en/docs/guide/threading)). ## Types | Type | Kind | Purpose | | ------------------------------------------------------------------------------------------------------------------ | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `World` | sealed class, `IDisposable` | Owns entities, components, singletons, indexes and systems. | | `WorldOptions` | sealed class | `ParallelSystems`, `MaxDegreeOfParallelism`, `InitialEntityCapacity`, `MeasureSystems`, `SystemErrors` (init-only). | | `Entity` | readonly struct | Handle: `Id`, `World`, `IsAlive`. A destroyed or default handle answers questions (`IsAlive`, `Has`, `TryGet`, `TryGetRef`) with false, throws on accesses and changes, and ignores `Destroy`. Converts to its `EntityId`. | | `EntityId` | readonly struct, unmanaged | `Index` and `Version`, 8 bytes: what a component stores to refer to an entity. `EntityId.Null` names none. | | `IComponent`, `ISingletonComponent` | marker interfaces | Component and singleton structs. An empty component is a tag. | | `ITrackChanges` | marker interface | Rows record the change tick of their last write or removal ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking)). | | `IIndexed` | interface | A component the world indexes by its `Key`; written with `Set` (EECS015). An `EntityId` key makes it a link to an entity. | | `IRelation` | interface | An element of a `DynamicBuffer` that links its entity to `Target` ([indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations)). | | `ChildOf` | record struct | `ChildOf(EntityId Parent)`: the hierarchy; destroying a parent destroys its children ([hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy)). | | `IGroup` | interface | A component whose `Group` value splits tables (`world.GroupBy()`, [groups](https://ecs.xgamedev.net/en/docs/guide/groups)). | | `ICleanupComponent`, `Destroyed` | marker interface, tag | An entity destroyed while it holds a cleanup component keeps it, tagged `Destroyed`, until it is removed ([cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable)). | | `Disabled` | tag | Present while `T` is disabled: the value kept, the component hidden. | | `Prefab` | sealed class | A recipe of component values that belongs to no world ([prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs)). | | `DynamicBuffer` | struct, `IComponent, ITrackChanges` | A list per entity; writes through `DynamicBufferExtensions` on a `ref` ([dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers)). | | `ValueIndex` | sealed class | `world.Index()`: `Find`, `TryFind`, `Count`; ordered walks for a comparable key (`OrderedIndexExtensions`). | | `RelationIndex` | sealed class | `world.Relations()`: the entities linking to a target. | | `TargetPolicy`, `TargetRules` | enum, extensions | What destroying a target does to the links to it: `Keep`, `Remove`, `Destroy`. | | `EcsSystem` | abstract class | `World`, `UpdateInterval`, `UpdatePhase`, `Enabled`, `Error`, `Stats`, `LastRunTick`; `OnCreate` / `OnUpdate` / `OnDestroy` ([systems](https://ecs.xgamedev.net/en/docs/guide/systems)). | | `ForEachAttribute` and its filters | attributes | `[ForEach]` (`Parallel = true`), `[With]`, `[Without]`, `[WithAny]`, `[Changed]`, `[Removed]`. | | `Maybe` | ref struct | An optional component parameter of a `[ForEach]` method: `HasValue`, `Value`. | | `ISystemGroup`, `IGroupWith`, `IGroupWithout`, `[UpdateInGroup]`, `[UpdateBefore]`, `[UpdateAfter]` | interfaces, attributes | System groups (with filters through interfaces) and ordering. | | `SystemErrorPolicy` | enum | `Throw` (default) or `Disable`: what an exception in a system does. | | `SystemStats`, `SystemList` | readonly structs | A system's run count and times; `world.Systems`, allocation-free. | | `SystemAccess` | struct | What a system reads and writes; filled only by generated code. | | `QueryFilter` | readonly struct | `With`, `Without`, `WithAny`, `Changed`, `Removed`, `InGroup`, `Since`; holds no object reference. | | `QueryEnumerator`, `QueryItem` | ref structs | The result of `Query`: `item.Entity` and refs into the row (`item.Position`). | | `IForEach<…>`, `IForEachEntity<…>`, `IForEachBatch<…>`, `INoStructuralChanges` | interfaces | Struct jobs for ad-hoc passes; `EntitySpan` holds a batch run's entities. | | `SingletonRef` | readonly struct | A stable singleton handle; `.Value` is `ref T`. | | `WorldSnapshot` | sealed class | A copy of a world in memory (`world.Capture()`). | | `TableInfo`, `ColumnInfo`, `ComponentValue` | record structs | What `world.Describe()` and `entity.Describe()` return. | ## Entities | API | Complexity | Notes | | ------------------------------------------------------------ | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `new World(options)` | O(`InitialEntityCapacity`) | `options` may be null (defaults); allocates the entity array and the empty table | | `world.CreateEntity()` | O(1) amortized | reuses recycled ids | | `world.CreateEntity(in T1 … in Tn)` | O(n) amortized | placed directly in its final table | | `world.CreateEntities(Span entities, in T1 … in Tn)` | O(count × n) amortized | one gate pass and at most one table growth for the wave; writes the handles | | `entity.Destroy()` | O(c) | the table's last row fills the hole (a tombstone during a pass); recycles the id; a stale handle is ignored; unlinks indexed components; cascades to `ChildOf` children and applies target policies | | `world.DestroyEntities(filter)` | O(M + S) | destroys every match in one gate pass and returns how many; safe during a pass | | `entity.IsAlive` / `world.IsAlive(id)` | O(1) | | | `world.TryGetEntity(id, out e)` / `GetEntity(id)` | O(1) | false (or a throw) when that incarnation is not alive | | `world.EntityCount` | O(1) | | | `world.Entities` | O(capacity) | living entities in id order, for diagnostics | | `world.EnsureEntityCapacity(capacity)` | O(capacity) | pre-size the entity array; a no-op when large enough | | `world.EnsureCapacity(count)` | O(n), plus one growth | pre-sizes the table of exactly `T1..Tn` and the entity array, so the next `count` creations with those components never grow them | ## Components | API | Complexity | Notes | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `entity.Get()` | O(1) | `ref T`: a version check, a column lookup, one presence-bit test, one load; throws if missing or not alive; a write of a tracked component | | `entity.Read()` | O(1) | `ref readonly T`; never a write | | `entity.TryGetRef(out bool found)` | O(1) | `ref T`, a null ref when missing; a write of a tracked component when found | | `entity.Has()` / `TryGet(out T)` | O(1) | false when missing or not alive; `TryGet` returns a copy (not a write) | | `entity.Has()` | O(n) | all of them, one record lookup | | `entity.Set(in T1 … in Tn)` | O(n), or O(c) amortized when it moves | adds or overwrites, at most one row copy, returns the entity; a component the table has a column for only sets its bit; re-indexes a changed key (O(1)) | | `entity.GetOrAdd()` | O(1); when missing, O(1) if the table has a column for `T`, else O(c) amortized | `ref T`; adds a default value only when missing; a write of a tracked component | | `entity.Remove()` | O(n) | clears presence bits, the row stays; missing components are ignored; a tracked component's removal is stamped (`[Removed]`); returns the entity | | `entity.Disable()` / `Enable()` | O(1); the first disable in a table moves the row once | keeps the value while queries, `Has` and `Get` see it as gone; a disable counts as a removal, an enable as a write; returns false when there was nothing to do | | `entity.IsDisabled()` | O(1) | | | generated: `entity.X`, `HasX`, `TryGetX`, `GetOrAddX()`, `SetX(…)`, `RemoveX()`, `WriteX()`, `DisableX()`, `EnableX()`, `IsXDisabled`; tags `IsX`, `SetX()`; `world.XIndex` | as the generic call | C# 14 extension members per component ([generated members](https://ecs.xgamedev.net/en/docs/guide/entities-and-components)); `entity.X` is `Get`, or `Read` for a tracked or indexed component, whose writes use `WriteX()` or `SetX(…)` | ## Prefabs and cloning A copy gets its own list for each `DynamicBuffer`, is indexed at once, and counts as a write of every tracked component it has; components the source lacks stay absent and are not removals. | API | Complexity | Notes | | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `new Prefab()` | O(1) | an empty recipe; allocates its private store once | | `new Prefab(basePrefab)` | O(c) | a variant: a copy of every value (and member), changed on its own afterwards | | `prefab.Set(in T1 … in Tn)` | O(n), or O(c) amortized when it gains a component | adds or replaces values; returns the prefab | | `prefab.Remove()` | O(n) | missing ones are ignored; returns the prefab | | `prefab.Has()` / `Read()` | O(1) | `Read` throws if the prefab has no `T` | | `prefab.SetBuffer(params ReadOnlySpan)` | O(n) | a `DynamicBuffer` of these elements; every instance gets a list of its own | | `prefab.AddMember()` | O(1) | a member of the prefab's group: instantiating one creates all; `EntityId` fields naming members are rewritten per instance | | generated: `prefab.X`, `HasX`, `SetX(…)`, `RemoveX()`; tags `IsX`, `SetX()`; buffers `SetLoot(items…)` | as the generic call | writers return the prefab; the property is read-only; not structural changes of any world | | `world.Instantiate(prefab)` | O(c) | one row copy; the target table is found once per prefab table and cached; safe during a pass (which does not visit the new entity); O(members × c) for a group | | `world.Instantiate(prefab, Span entities)` | O(count × c) | one gate pass and at most one table growth for the wave | | `world.EnsureCapacity(prefab, count)` | O(c), plus one growth | pre-sizes the tables the next `count` instances go to, so a spawn wave never grows them during a tick | | `entity.Clone()` | O(c) | a new entity of the same world and table with a copy of every component; throws if not alive | ## Dynamic buffers `new DynamicBuffer()` holds no list until its first write. Reads work on any reference (`in`, `Read()`); writes need a `ref` and are tracked writes. | API | Complexity | Notes | | ---------------------------------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------ | | `bag.Count`, `bag.Capacity`, `bag[i]`, `AsReadOnlySpan()`, `GetEnumerator()` | O(1) | read-only; out-of-range indexes throw | | `bag.Add(item)` / `AddRange(span)` | O(1) amortized / O(items) | allocates only when the list grows | | `bag.Insert(i, item)` / `RemoveAt(i)` | O(count) | keep the order | | `bag.RemoveAtSwapBack(i)` | O(1) | the last element moves into `i` | | `bag.Clear()` | O(1), O(count) for elements with references | keeps the capacity | | `bag.EnsureCapacity(n)` / `AsSpan()` | O(count) when it grows / O(1) | `AsSpan()` is writable | | `bag.TrimExcess()` | O(count) | reallocates to the count; an empty list holds no array | A snapshot, a save or a clone of a buffer column copies the elements: O(elements), a new list per entity. ## Queries | API | Complexity | Notes | | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `[ForEach]` method / `world.ForEach(ref job, filter)` | O(M + S) | fastest: a struct job, no delegate | | `world.ForEachEntity(ref job, filter)` | O(M + S) | the job also receives the `Entity` | | `entity.Run(ref job)` / `Run(ref job, filter)` | O(n), plus O(1) per filter component | one entity; false when stale, missing a component or rejected by the filter; refs survive the job's structural changes | | `world.ForEachBatch(ref job, filter)` | O(M + S / 64 + runs) | spans of consecutive rows; no structural changes | | `world.ForEachParallel(ref job, filter)` / `ForEachEntityParallel` | O(M + S), divided over up to `MaxDegreeOfParallelism` threads | `INoStructuralChanges` jobs; chunks of 1,024 to `World.ParallelChunkRows` rows, one job copy per chunk; helpers are woken only when they pay | | `foreach (var item in world.Query(filter))` | O(M + S) | refs into the row: every visited row of a tracked component counts as written; no `await` in the loop | | `world.Count(filter)` | O(M), + S / 64 for tables whose rows must be tested | sums table counts, or counts presence bits (and ticks), 8 words per step with AVX-512 | | `world.Any(filter)` | O(M + S / 64) worst | stops at the first match | | `QueryFilter.Create().With().Without().WithAny()` | O(1) | build once, keep in a `static readonly` field; `WithAny` calls form one "at least one of" group | | `filter.Changed(since)` / `[Changed]` | O(1); a pass skips tables, 4,096-row blocks and 64-row words written before `since` | rows whose tracked `T` was written at or after `since` ([change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking)); one tick per filter | | `filter.Removed(since)` / `[Removed]` | as `Changed` | entities that lost a tracked `T` at or after `since` and still lack it; destroyed entities are not reported | | `filter.InGroup(group)` | O(1); a pass walks only that group's tables | [groups](https://ecs.xgamedev.net/en/docs/guide/groups) | | `filter.Since(since)` | O(1) | the filter with its `Changed` and `Removed` ticks moved, without rebuilding it | The first use of a query shape builds its cache entry, O(all tables), under the shared gate. Later lookups are a memo hit or one hash probe. Creating a new table (the first entity with a new component set) costs O(tables + cached query shapes), as it joins every cached query it matches. Both are cold paths. ## Disable and bulk changes | API | Complexity | Notes | | ------------------------------------------------------ | ---------- | -------------------------------------------------------------------------------------------------- | | `world.SetAll(in T value, filter)` | O(M + S) | `Set` on every match, a word of rows at a time; an entity lacking `T` moves once; returns how many | | `world.RemoveAll(filter)` | O(M + S) | rows stay, presence bits clear; returns how many | | `world.DisableAll(filter)` / `EnableAll(filter)` | O(M + S) | a table's rows move once, to the table with the `Disabled` column; returns how many | Details: [bulk changes](https://ecs.xgamedev.net/en/docs/guide/bulk), [cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable). ## Indexes | API | Complexity | Notes | | ----------------------------------------------------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `world.Index()` | O(1); the first call creates it | one per world and indexed component; a second key type throws | | `index.Count(key)` / `TryFind(key, out Entity)` | O(1) | a hash probe (an array access for a key that is an entity); the first lookup indexes every row once | | `index.Find(key)` | O(1), then O(1) per entity | a `ref struct` for `foreach`; destroying entities during the loop is allowed, changing `T` is not | | `index.Ascending()` / `Descending()` | O(keys log keys) for the first walk, then O(1) per entity | ordered walks for a comparable key (leaderboards, timers); after the first walk the index keeps its keys sorted: O(log keys) plus a block move per key that appears or disappears | | `index.Range(min, max)` / `RangeDescending(min, max)` | O(keys log keys) for the first walk, then O(log keys) to find `min` and O(1) per entity | inclusive bounds | | `index.WhenTargetDestroyed(policy)` | O(1); then O(1) per destroyed entity | an `EntityId` key: `Keep` (default), `Remove` or `Destroy` the components pointing at a destroyed entity | ## Hierarchy and relations | API | Complexity | Notes | | ------------------------------------------------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------- | | `world.Children(parent)` | O(1), then O(1) per child | the entities whose `ChildOf` points at `parent`; destroying a parent destroys them, and theirs | | `world.Descendants(root)` | O(1) per entity of the subtree | depth first, every level below `root`; 0 B once warm | | `entity.AddRelation(in T relation)` | O(1) amortized | appends to the entity's `DynamicBuffer` (added first if missing) and to the relation index | | `entity.RemoveRelation(target)` / `HasRelation(target)` | O(L) | `RemoveRelation` returns how many links went | | `world.Relations()` | O(1); the first call creates it | the relation index; generated as `world.XIndex` for a relation `X` | | `relations.Count(target)` | O(1) | links to `target` | | `relations.Find(target)` | O(1), then O(1) per link | the entities linking to `target` | | `relations.WhenTargetDestroyed(policy)` | O(1); then O(1) per destroyed entity and O(L) per link | `Remove` drops the links, `Destroy` destroys the linking entities | ## Groups | API | Complexity | Notes | | -------------------- | -------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `world.GroupBy()` | O(entities with `T`), once | splits tables by `T.Group`; setting a new value moves the entity to its group's tables (one row copy); call it at setup | ## Snapshots, saves and moves | API | Complexity | Notes | | ------------------------------------------------------ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `world.Capture()` / `Capture(into)` | O(entities × components + tables + singletons) | copies by value; `Capture(into)` reuses an earlier snapshot's arrays and allocates nothing once they are large enough; not while a pass iterates | | `world.Restore(snapshot)` | O(entities × components + tables + singletons) | snapshot handles are valid again, later ones stale; every restored row counts as written (or removed) | | `world.Save(output)` | O(entities × components) | the world as bytes: unmanaged rows raw, managed values through Nino; allocates nothing once its buffers are large enough | | `world.Load(input, markWritten)` | O(entities × components) | entities keep their ids; a changed component layout throws `InvalidDataException` and leaves the world as it was; `markWritten: false`: the loaded rows count as never written | | `world.SaveEntities(output, ids)` | O(entities given × components) | a group of entities, for another world or process | | `world.SaveEntities(output, ids, set)` | O(entities given × components) | only the components of a `ComponentSet` (built once: `ComponentSet.Create().With()`, O(1) per type) | | `world.LoadEntities(input, entities)` | O(entities × components) | new ids; `EntityId` fields naming the group are rewritten, others become `EntityId.Null` | | `world.LoadEntitiesInto(input, entities, markWritten)` | O(entities × components) | onto entities that exist: each moves table at most once, the components the save lacks stay; `markWritten: false`: the loaded components count as never written | | `world.MoveEntities(target, ids, moved)` | O(entities × components) | to another world of this thread, without encoding; the originals are destroyed | Details: [snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots), [saves](https://ecs.xgamedev.net/en/docs/guide/saves), [migration and unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload). ## Systems, singletons, maintenance | API | Complexity | Notes | | --------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `world.AddSystem(changesFromNow)` / `AddSystem(system, changesFromNow)` | O(s²), s = systems of its group | calls `OnCreate`; rebuilds the order and stages (cold); throws if the system already belongs to a world, or on an ordering cycle; `changesFromNow: true`: its first run sees only what is written after the call | | `world.RemoveSystem()` | O(s²) | calls `OnDestroy`; returns whether a system was removed | | `world.GetSystem()` | O(systems) | null when absent | | `world.Update()` / `world.Update()` | Σ systems of the group | synchronous, allocation-free; throws `ObjectDisposedException` after `Dispose` | | `world.ChangeTick` | O(1) | grows by one per stage of systems and once after each update | | `world.AddSingleton()` / `GetSingleton()` / `GetOrAddSingleton()` | O(1) | `ref T`; `AddSingleton` resets an existing singleton in place; `GetSingleton` throws when missing | | `world.SingletonRef()` | O(1) | a stable handle; throws when the singleton was not added; `.Value` is one load | | `world.TryGetSingleton(out T)` / `HasSingleton()` / `RemoveSingleton()` | O(1) | `RemoveSingleton` returns false when it was not added | | generated: `world.X`, `HasX`, `GetOrAddX()`, `SetX(…)`, `RemoveX()` for a singleton `X` | as the generic call | | | `world.Systems` | O(systems) to walk, `Count` O(groups) | every group's systems in execution order, allocation-free | | `world.UpdateCount` | O(1) | default-group updates so far | | `world.RemoveTypes(assembly)` / `RemoveTypes(context)` | O(entities with such components + tables + cached queries) | takes a plugin's systems, singletons, indexes and components out of the world so its `AssemblyLoadContext` can unload; allocates (cold) | | `world.Describe()` | O(tables + columns) | every table with its columns, rows, capacity and bytes; allocates (cold) | | `entity.Describe()` | O(c) | boxed copies of the entity's components, disabled ones marked; allocates (cold) | | `world.Dispose()` | O(systems + entities + tables) | `OnDestroy` on every system in reverse order, then releases storage | `WorldOptions.SystemErrors`: `SystemErrorPolicy.Throw` (default: the exception propagates out of `Update()`, and of `Dispose` for `OnDestroy`) or `Disable` (the system is switched off and keeps the exception in `system.Error` until it is enabled again; a failed run still moves `LastRunTick` on). `WorldOptions.MeasureSystems` times every run into `system.Stats` (`Runs`, `Last`, `Total`, `Average`) for two timestamp reads per run. Values and handles, all O(1): `entity.Id` / `World`, `id.Index` / `Version`, `==` / `Equals` / `GetHashCode` (id and version) / `ToString`; `snapshot.EntityCount`; `system.LastRunTick`, `UpdateInterval`, `UpdatePhase`, `Enabled`, `Error`, `Stats`, `World`. ## Related - [API reference](https://ecs.xgamedev.net/en/docs/reference): Every public type and member with its signature, generated from the XML documentation. - [Performance](https://ecs.xgamedev.net/en/docs/performance): Which of these calls to use when, measured. - [Architecture](https://ecs.xgamedev.net/en/docs/architecture): The structures behind these complexities. --- # API reference > Every public type of EasyEcs.Core with its members, generated from the XML documentation. URL: https://ecs.xgamedev.net/en/docs/reference Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference.md Everything is in `namespace EasyEcs`. These pages are generated from the XML documentation of `EasyEcs.Core`; the members the generator writes for your own components (`entity.Position`, `world.Clock`, `SetDead()`) are in [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components#generated-members), and the complexity of every call in [API and complexity](https://ecs.xgamedev.net/en/docs/api). ## Classes | Type | Summary | | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`ChangedAttribute`](https://ecs.xgamedev.net/en/docs/reference/changedattribute) | The ForEachAttribute method visits only entities whose T was written since its system last ran (EcsSystem.LastRunTick; on the first run, every entity having it). | | [`DynamicBufferExtensions`](https://ecs.xgamedev.net/en/docs/reference/dynamicbufferextensions) | The writes of a DynamicBuffer. | | [`EcsSystem`](https://ecs.xgamedev.net/en/docs/reference/ecssystem) | Logic that runs on a world. | | [`ForEachAttribute`](https://ecs.xgamedev.net/en/docs/reference/foreachattribute) | Runs a method of an EcsSystem (or a static method of any other type, through a generated entry point) for every entity matching its component parameters (and the WithAttribute / WithoutAttribute / WithAnyAttribute filters), each update, after EcsSystem.OnUpdate, in declaration order. | | [`OrderedIndexExtensions`](https://ecs.xgamedev.net/en/docs/reference/orderedindexextensions) | Ordered walks of a value index whose key is comparable (a score, a deadline, a level): ranges and sorted iteration for leaderboards, timers and matchmaking brackets. | | [`Prefab`](https://ecs.xgamedev.net/en/docs/reference/prefab) | A recipe for entities: a set of component values that belongs to no world, so no query ever sees it. | | [`RelationIndex`](https://ecs.xgamedev.net/en/docs/reference/relationindex) | The links of relation T in one world, by target (World.Relations): which entities link to an entity, O(1) to start and O(1) per link. | | [`RemovedAttribute`](https://ecs.xgamedev.net/en/docs/reference/removedattribute) | The ForEachAttribute method visits only entities that lost T since its system last ran (EcsSystem.LastRunTick) and have not got it back: replication sends the removal, a cleanup releases what the component stood for. | | [`TargetRules`](https://ecs.xgamedev.net/en/docs/reference/targetrules) | Target policies of components that point at an entity (IIndexed of EntityId). | | [`UpdateAfterAttribute`](https://ecs.xgamedev.net/en/docs/reference/updateafterattribute) | Run this system after TSystem (and systems derived from it) of the same group: see UpdateBeforeAttribute. | | [`UpdateBeforeAttribute`](https://ecs.xgamedev.net/en/docs/reference/updatebeforeattribute) | Run this system before TSystem (and systems derived from it) of the same group, whatever their registration order. | | [`UpdateInGroupAttribute`](https://ecs.xgamedev.net/en/docs/reference/updateingroupattribute) | Puts the system (and derived systems) into group TGroup. | | [`ValueIndex`](https://ecs.xgamedev.net/en/docs/reference/valueindex) | The value index of component T in one world (World.Index). | | [`WithAnyAttribute`](https://ecs.xgamedev.net/en/docs/reference/withanyattribute) | The ForEachAttribute method requires at least one of the components named by its [WithAny] attributes (not passed in): [ForEach, WithAny, WithAny]. | | [`WithAttribute`](https://ecs.xgamedev.net/en/docs/reference/withattribute) | The ForEachAttribute method also requires component T (not passed in). | | [`WithoutAttribute`](https://ecs.xgamedev.net/en/docs/reference/withoutattribute) | The ForEachAttribute method skips entities having component T. | | [`World`](https://ecs.xgamedev.net/en/docs/reference/world) | An ECS world: entities, their components, singletons and the systems that update them. | | [`WorldOptions`](https://ecs.xgamedev.net/en/docs/reference/worldoptions) | Configuration of a World. | | [`WorldSnapshot`](https://ecs.xgamedev.net/en/docs/reference/worldsnapshot) | A copy of a world's entities, components and singletons, taken by World.Capture and put back by World.Restore (systems and options are not part of it). | ## Structs | Type | Summary | | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) | The hierarchy relation: the entity is a child of ChildOf.Parent. | | [`ColumnInfo`](https://ecs.xgamedev.net/en/docs/reference/columninfo) | A column of a table (TableInfo). | | [`ComponentSet`](https://ecs.xgamedev.net/en/docs/reference/componentset) | A set of component types, built once and kept (a static readonly field): the components a save writes (World.SaveEntities), the record of what persists without the runtime state around it. | | [`ComponentValue`](https://ecs.xgamedev.net/en/docs/reference/componentvalue) | A component of an entity, as Entity.Describe reads it: a boxed copy of its value. | | [`Destroyed`](https://ecs.xgamedev.net/en/docs/reference/destroyed) | Tag of an entity that was destroyed while holding ICleanupComponents: its other components are gone, it stays alive until its last cleanup component is removed. | | [`Disabled`](https://ecs.xgamedev.net/en/docs/reference/disabled) | The tag of an entity whose T is disabled (Entity.Disable): the entity keeps the value of T but lacks it for queries, Has and Get until Entity.Enable gives it back. | | [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer) | A list of T per entity, held as a component: an inventory, a path, the hits of this tick. | | [`Entity`](https://ecs.xgamedev.net/en/docs/reference/entity) | Handle to an entity: id + version + world (16 bytes). | | [`EntityId`](https://ecs.xgamedev.net/en/docs/reference/entityid) | The identity of an entity: its index and the incarnation of that index (8 bytes, unmanaged). | | [`EntitySpan`](https://ecs.xgamedev.net/en/docs/reference/entityspan) | The entities of one run of rows in a batch job: element i is the entity whose components are element i of the run's spans. | | [`Maybe`](https://ecs.xgamedev.net/en/docs/reference/maybe) | An optional component of the entity a [ForEach] method visits: static void Regen(ref Health h, Maybe buff) visits every entity with Health, and Maybe.HasValue tells whether this one also has a Buff. | | [`QueryEnumerator`](https://ecs.xgamedev.net/en/docs/reference/queryenumerator) | Allocation-free query enumerator; safe under structural changes during iteration (same visiting rules as ForEach). | | [`QueryFilter`](https://ecs.xgamedev.net/en/docs/reference/queryfilter) | Extra query constraints: components that must be present without being read (QueryFilter.With) or must be absent (QueryFilter.Without). | | [`QueryItem`](https://ecs.xgamedev.net/en/docs/reference/queryitem) | One query result: the entity and refs into its row. | | [`RelationIndex.Sources`](https://ecs.xgamedev.net/en/docs/reference/relationindex-sources) | Enumerates the entities linking to one target (foreach), once per link. | | [`SingletonRef`](https://ecs.xgamedev.net/en/docs/reference/singletonref) | Handle to one world's singleton T. | | [`SystemAccess`](https://ecs.xgamedev.net/en/docs/reference/systemaccess) | The data a system reads and writes, declared once when the system is added. | | [`SystemList`](https://ecs.xgamedev.net/en/docs/reference/systemlist) | The systems of a world, every group in execution order (default group first): foreach it, or read SystemList.Count. | | [`SystemList.Enumerator`](https://ecs.xgamedev.net/en/docs/reference/systemlist-enumerator) | Walks the groups and their systems. | | [`SystemStats`](https://ecs.xgamedev.net/en/docs/reference/systemstats) | How often and how long a system ran (WorldOptions.MeasureSystems): EcsSystem.OnUpdate plus its [ForEach] methods, per run. | | [`TableInfo`](https://ecs.xgamedev.net/en/docs/reference/tableinfo) | A table: the entities with one set of component columns (World.Describe). | | [`ValueIndex.Matches`](https://ecs.xgamedev.net/en/docs/reference/valueindex-matches) | Enumerates the entities of one key (foreach). | | [`ValueIndex.Ordered`](https://ecs.xgamedev.net/en/docs/reference/valueindex-ordered) | Enumerates entities in key order (foreach): every entity of a key, then the next key. | | [`World.DescendantWalk`](https://ecs.xgamedev.net/en/docs/reference/world-descendantwalk) | A depth-first walk of World.Descendants: a stack of the child lists still being read, given back to the world by World.DescendantWalk.Dispose (foreach calls it). | | [`World.EntityEnumerator`](https://ecs.xgamedev.net/en/docs/reference/world-entityenumerator) | Enumerates alive entities in id order; ids beyond the capacity captured at start are not visited. | | [`World.Subtree`](https://ecs.xgamedev.net/en/docs/reference/world-subtree) | The descendants of an entity (World.Descendants): each foreach walks them anew. | ## Interfaces | Type | Summary | | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`ICleanupComponent`](https://ecs.xgamedev.net/en/docs/reference/icleanupcomponent) | Marks a component that outlives the destruction of its entity: destroying an entity holding one removes its other components and adds the Destroyed tag instead of freeing it, so a system can release what the component stands for (a socket, a reservation, a slot in another service) and then remove it. | | [`IComponent`](https://ecs.xgamedev.net/en/docs/reference/icomponent) | Marks a struct as component data. | | [`IForEach`](https://ecs.xgamedev.net/en/docs/reference/iforeach) | Struct callback for World.ForEach. | | [`IForEachBatch`](https://ecs.xgamedev.net/en/docs/reference/iforeachbatch) | Struct callback for World.ForEachBatch: receives whole runs of rows as spans, one per component, so the job can process them with SIMD (System.Numerics.Vector, MemoryMarshal.Cast), and their entities (built only when indexed). | | [`IForEachEntity`](https://ecs.xgamedev.net/en/docs/reference/iforeachentity) | Like IForEach but also receives the Entity handle, built from the archetype's entity rows (id and version side by side) without a per-entity lookup. | | [`IGroup`](https://ecs.xgamedev.net/en/docs/reference/igroup) | Marks a component whose value splits tables: in a world that called World.GroupBy, entities with different IGroup.Groups live in different tables, so a query of one group (QueryFilter.InGroup) walks only its own rows, contiguous in memory (a zone, a map, a match, a team). | | [`IGroupWith`](https://ecs.xgamedev.net/en/docs/reference/igroupwith) | A system group whose [ForEach] methods visit only entities with T, as WithAttribute on the group would. | | [`IGroupWithout`](https://ecs.xgamedev.net/en/docs/reference/igroupwithout) | A system group whose [ForEach] methods skip entities with T, as WithoutAttribute on the group would (see IGroupWith). | | [`IIndexed, IIndexed`](https://ecs.xgamedev.net/en/docs/reference/iindexed) | What every IIndexed is, so a component type is known to be indexed without reflection (a type test the JIT folds). | | [`INoStructuralChanges`](https://ecs.xgamedev.net/en/docs/reference/inostructuralchanges) | Marks a ForEach job that makes no structural change (no create/destroy/add/remove/set on any entity of the world it iterates). | | [`IRelation`](https://ecs.xgamedev.net/en/docs/reference/irelation) | An element of a DynamicBuffer that links its entity to IRelation.Target: an entity holds any number of links of one kind (the members of a party, the items a merchant offers, the units a buff applies to), and World.Relations finds the entities linking to a target. | | [`ISingletonComponent`](https://ecs.xgamedev.net/en/docs/reference/isingletoncomponent) | Marks a struct as a world singleton: exactly one value per world (clock, configuration, shared state). | | [`ISystemGroup`](https://ecs.xgamedev.net/en/docs/reference/isystemgroup) | Marker of a system group: systems marked UpdateInGroupAttribute run together when World.Update is called, independently of the default group run by World.Update. | | [`ITrackChanges`](https://ecs.xgamedev.net/en/docs/reference/itrackchanges) | Marks a component whose changes are tracked: every row records the world's World.ChangeTick of its last write, and [Changed] / QueryFilter.Changed(since) select the rows written since a system last ran. | ## Enums | Type | Summary | | ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | | [`SystemErrorPolicy`](https://ecs.xgamedev.net/en/docs/reference/systemerrorpolicy) | What an exception thrown by a system does (WorldOptions.SystemErrors). | | [`TargetPolicy`](https://ecs.xgamedev.net/en/docs/reference/targetpolicy) | What happens to the links to an entity when it is destroyed (TargetRules.WhenTargetDestroyed, RelationIndex.WhenTargetDestroyed). | ## Delegates | Type | Summary | | ------------------------------------------------------------------------------ | ------------------------------------------------------ | | [`EntityIdField`](https://ecs.xgamedev.net/en/docs/reference/entityidfield) | An EntityId field of value (see SavedTypes.EntityIds). | --- # ChangedAttribute > The ForEachAttribute method visits only entities whose T was written since its system last ran (EcsSystem.LastRunTick… URL: https://ecs.xgamedev.net/en/docs/reference/changedattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/changedattribute.md ```csharp public sealed class ChangedAttribute : Attribute where T : struct, IComponent, ITrackChanges ``` The [`ForEachAttribute`](https://ecs.xgamedev.net/en/docs/reference/foreachattribute) method visits only entities whose `T` was written since its system last ran ([`EcsSystem.LastRunTick`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#lastruntick); on the first run, every entity having it). Requires `T` like [`WithAttribute`](https://ecs.xgamedev.net/en/docs/reference/withattribute); `T` tracks changes ([`ITrackChanges`](https://ecs.xgamedev.net/en/docs/reference/itrackchanges)). Several attributes require all of the components to have changed. ## Constructors ### `ChangedAttribute` ```csharp public ChangedAttribute(); ``` --- # ChildOf > The hierarchy relation: the entity is a child of ChildOf.Parent. The ChildOf struct of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/childof Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/childof.md ```csharp public struct ChildOf : IComponent, IIndexed, IIndexed, IEquatable ``` The hierarchy relation: the entity is a child of [`ChildOf.Parent`](https://ecs.xgamedev.net/en/docs/reference/childof#parent). Destroying a parent destroys its children, and theirs ([`World.Children`](https://ecs.xgamedev.net/en/docs/reference/world#children) lists them). An indexed relation like any other: write it with `Set`, re-parent by setting a new value, detach by removing it. ## Constructors ### `ChildOf` ```csharp public ChildOf(EntityId Parent); ``` The hierarchy relation: the entity is a child of [`ChildOf.Parent`](https://ecs.xgamedev.net/en/docs/reference/childof#parent). Destroying a parent destroys its children, and theirs ([`World.Children`](https://ecs.xgamedev.net/en/docs/reference/world#children) lists them). An indexed relation like any other: write it with `Set`, re-parent by setting a new value, detach by removing it. ## Properties ### `Key` ```csharp public EntityId Key { get; } ``` ### `Parent` ```csharp public EntityId Parent { readonly get; set; } ``` ## Methods ### `Deconstruct` ```csharp public readonly void Deconstruct(out EntityId Parent); ``` ### `Equals` ```csharp public override readonly bool Equals(object obj); public readonly bool Equals(ChildOf other); ``` ### `GetHashCode` ```csharp public override readonly int GetHashCode(); ``` ### `ToString` ```csharp public override string ToString(); ``` ## Operators ### `operator !=` ```csharp public static bool operator !=(ChildOf left, ChildOf right); ``` ### `operator ==` ```csharp public static bool operator ==(ChildOf left, ChildOf right); ``` --- # ColumnInfo > A column of a table (TableInfo). The ColumnInfo struct of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/columninfo Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/columninfo.md ```csharp public readonly struct ColumnInfo : IEquatable ``` A column of a table ([`TableInfo`](https://ecs.xgamedev.net/en/docs/reference/tableinfo)). #### Parameters - `Type`: The component type. - `Without`: Living rows of the table without the component (removed or disabled: no row moved). - `Group`: The group every row of the table is in, for an [`IGroup`](https://ecs.xgamedev.net/en/docs/reference/igroup) component; else 0. ## Constructors ### `ColumnInfo` ```csharp public ColumnInfo(Type Type, int Without, int Group); ``` A column of a table ([`TableInfo`](https://ecs.xgamedev.net/en/docs/reference/tableinfo)). **Parameters** - `Type`: The component type. - `Without`: Living rows of the table without the component (removed or disabled: no row moved). - `Group`: The group every row of the table is in, for an [`IGroup`](https://ecs.xgamedev.net/en/docs/reference/igroup) component; else 0. ## Properties ### `Group` ```csharp public int Group { get; init; } ``` The group every row of the table is in, for an [`IGroup`](https://ecs.xgamedev.net/en/docs/reference/igroup) component; else 0. ### `Type` ```csharp public Type Type { get; init; } ``` The component type. ### `Without` ```csharp public int Without { get; init; } ``` Living rows of the table without the component (removed or disabled: no row moved). ## Methods ### `Deconstruct` ```csharp public void Deconstruct(out Type Type, out int Without, out int Group); ``` ### `Equals` ```csharp public bool Equals(ColumnInfo other); public override bool Equals(object obj); ``` ### `GetHashCode` ```csharp public override int GetHashCode(); ``` ### `ToString` ```csharp public override string ToString(); ``` ## Operators ### `operator !=` ```csharp public static bool operator !=(ColumnInfo left, ColumnInfo right); ``` ### `operator ==` ```csharp public static bool operator ==(ColumnInfo left, ColumnInfo right); ``` --- # ComponentSet > A set of component types, built once and kept (a static readonly field)… URL: https://ecs.xgamedev.net/en/docs/reference/componentset Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/reference/componentset.md ```csharp public readonly struct ComponentSet ``` A set of component types, built once and kept (a `static readonly` field): the components a save writes ([`World.SaveEntities`](https://ecs.xgamedev.net/en/docs/reference/world#saveentities-2)), the record of what persists without the runtime state around it. `ComponentSet.Create().With().With()`; a framework that learns its types at registration adds them by `Type`. Each call returns a new set. ## Methods ### `Contains` ```csharp public bool Contains() where T : struct, IComponent; ``` Whether the set holds `T`. O(1). ### `Create` ```csharp public static ComponentSet Create(); ``` The empty set: the start of a chain. O(1). ### `With` ```csharp public ComponentSet With(Type type); ``` This set and component type `type` (a struct implementing [`IComponent`](https://ecs.xgamedev.net/en/docs/reference/icomponent)). Cold: one lookup. **Exceptions** - `ArgumentException`: `type` is not a component type the generator or a world registered. ### `With` ```csharp public ComponentSet With() where T : struct, IComponent; ``` This set and `T`. O(1). --- # ComponentValue > A component of an entity, as Entity.Describe reads it: a boxed copy of its value. URL: https://ecs.xgamedev.net/en/docs/reference/componentvalue Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/componentvalue.md ```csharp public readonly struct ComponentValue : IEquatable ``` A component of an entity, as [`Entity.Describe`](https://ecs.xgamedev.net/en/docs/reference/entity#describe) reads it: a boxed copy of its value. #### Parameters - `Value`: The value, boxed. - `Enabled`: False for a disabled component ([`Entity.Disable`](https://ecs.xgamedev.net/en/docs/reference/entity#disable)), whose value is kept. ## Constructors ### `ComponentValue` ```csharp public ComponentValue(object Value, bool Enabled); ``` A component of an entity, as [`Entity.Describe`](https://ecs.xgamedev.net/en/docs/reference/entity#describe) reads it: a boxed copy of its value. **Parameters** - `Value`: The value, boxed. - `Enabled`: False for a disabled component ([`Entity.Disable`](https://ecs.xgamedev.net/en/docs/reference/entity#disable)), whose value is kept. ## Properties ### `Enabled` ```csharp public bool Enabled { get; init; } ``` False for a disabled component ([`Entity.Disable`](https://ecs.xgamedev.net/en/docs/reference/entity#disable)), whose value is kept. ### `Value` ```csharp public object Value { get; init; } ``` The value, boxed. ## Methods ### `Deconstruct` ```csharp public void Deconstruct(out object Value, out bool Enabled); ``` ### `Equals` ```csharp public bool Equals(ComponentValue other); public override bool Equals(object obj); ``` ### `GetHashCode` ```csharp public override int GetHashCode(); ``` ### `ToString` ```csharp public override string ToString(); ``` ## Operators ### `operator !=` ```csharp public static bool operator !=(ComponentValue left, ComponentValue right); ``` ### `operator ==` ```csharp public static bool operator ==(ComponentValue left, ComponentValue right); ``` --- # Destroyed > Tag of an entity that was destroyed while holding ICleanupComponents: its other components are gone, it stays alive until its last cleanup component is removed. URL: https://ecs.xgamedev.net/en/docs/reference/destroyed Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/destroyed.md ```csharp public struct Destroyed : IComponent ``` Tag of an entity that was destroyed while holding [`ICleanupComponent`](https://ecs.xgamedev.net/en/docs/reference/icleanupcomponent)s: its other components are gone, it stays alive until its last cleanup component is removed. Select such entities with `With` (a cleanup system) and new ones with `Without` (an acquiring system). --- # Disabled > The tag of an entity whose T is disabled (Entity.Disable): the entity keeps the value of T but lacks it for queries… URL: https://ecs.xgamedev.net/en/docs/reference/disabled Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/disabled.md ```csharp public struct Disabled : IComponent where T : struct, IComponent ``` The tag of an entity whose `T` is disabled ([`Entity.Disable`](https://ecs.xgamedev.net/en/docs/reference/entity#disable)): the entity keeps the value of `T` but lacks it for queries, `Has` and `Get` until [`Entity.Enable`](https://ecs.xgamedev.net/en/docs/reference/entity#enable) gives it back. Query it like any tag (`[With>]`) to find the entities whose `T` is paused. Change it only through `Disable` and `Enable`. --- # DynamicBuffer > A list of T per entity, held as a component: an inventory, a path, the hits of this tick. URL: https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/dynamicbuffer.md ```csharp public struct DynamicBuffer : IComponent, ITrackChanges ``` A list of `T` per entity, held as a component: an inventory, a path, the hits of this tick. Writes go through a `ref` to the component (`ref` parameters of `[ForEach]` methods and jobs, [`Entity.Get`](https://ecs.xgamedev.net/en/docs/reference/entity#get)), so they are tracked like any write of an [`ITrackChanges`](https://ecs.xgamedev.net/en/docs/reference/itrackchanges) component and `[Changed>]` selects the entities whose list changed. Through `in` or [`Entity.Read`](https://ecs.xgamedev.net/en/docs/reference/entity#read) the list is read-only: the mutating methods ([`DynamicBufferExtensions`](https://ecs.xgamedev.net/en/docs/reference/dynamicbufferextensions)) take `ref this`, so a write through a read-only reference does not compile. Snapshots copy the elements ([`World.Capture`](https://ecs.xgamedev.net/en/docs/reference/world#capture)); a moved row keeps its list. Adding within the capacity allocates nothing. #### Remarks A `new DynamicBuffer()` holds no list: each entity's list is made by its first write (reserve room with [`DynamicBufferExtensions.EnsureCapacity`](https://ecs.xgamedev.net/en/docs/reference/dynamicbufferextensions#ensurecapacity)), so one value can create many entities. The list lives in an object the component refers to, and a copy of the component would refer to the same list: the analyzer rejects copies (EECS012), reach the list through the entity. ## Properties ### `Capacity` ```csharp public readonly int Capacity { get; } ``` The number of elements the list holds before it grows. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Count` ```csharp public readonly int Count { get; } ``` The number of elements. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ## Indexers ### `this[]` ```csharp public readonly ref readonly T this[int index] { get; } ``` The element at `index`, read-only (write through [`DynamicBufferExtensions.AsSpan`](https://ecs.xgamedev.net/en/docs/reference/dynamicbufferextensions#asspan)). ## Methods ### `AsReadOnlySpan` ```csharp public readonly ReadOnlySpan AsReadOnlySpan(); ``` The elements, read-only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `GetEnumerator` ```csharp public readonly ReadOnlySpan.Enumerator GetEnumerator(); ``` Enumerates the elements (read-only, no allocation). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) --- # DynamicBufferExtensions > The writes of a DynamicBuffer. The DynamicBufferExtensions class of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/dynamicbufferextensions Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/dynamicbufferextensions.md ```csharp public static class DynamicBufferExtensions ``` The writes of a [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer). Each takes the buffer by `ref`: it must be reached through a write access (a tracked change), never through `in`. ## Methods ### `Add` ```csharp public static void Add(this ref DynamicBuffer buffer, in T item); ``` Append `item`. O(1) amortized; allocates only when the list grows. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) amortized / O(items) ### `AddRange` ```csharp public static void AddRange(this ref DynamicBuffer buffer, ReadOnlySpan items); ``` Append `items`. O(items). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) amortized / O(items) ### `AsSpan` ```csharp public static Span AsSpan(this ref DynamicBuffer buffer); ``` The elements, writable. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(count) when it grows / O(1) ### `Clear` ```csharp public static void Clear(this ref DynamicBuffer buffer); ``` Remove every element; the capacity stays. O(1), or O(count) for elements holding references. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1), O(count) for elements with references ### `EnsureCapacity` ```csharp public static void EnsureCapacity(this ref DynamicBuffer buffer, int capacity); ``` Make room for at least `capacity` elements. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(count) when it grows / O(1) ### `Insert` ```csharp public static void Insert(this ref DynamicBuffer buffer, int index, in T item); ``` Insert `item` at `index`, keeping the order. O(count). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(count) ### `RemoveAt` ```csharp public static void RemoveAt(this ref DynamicBuffer buffer, int index); ``` Remove the element at `index`, keeping the order. O(count). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(count) ### `RemoveAtSwapBack` ```csharp public static void RemoveAtSwapBack(this ref DynamicBuffer buffer, int index); ``` Remove the element at `index` by moving the last one into its place. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `TrimExcess` ```csharp public static void TrimExcess(this ref DynamicBuffer buffer); ``` Shrink the capacity to the count, so a list that once grew large stops holding its peak (the list's array is reallocated; an empty list holds none). O(count). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(count) --- # EcsSystem > Logic that runs on a world. The EcsSystem class of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/ecssystem Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/ecssystem.md ```csharp public abstract class EcsSystem ``` Logic that runs on a world. Lifecycle: [`EcsSystem.OnCreate`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#oncreate) when added, then every update [`EcsSystem.OnUpdate`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#onupdate) followed by the [[ForEach]](https://ecs.xgamedev.net/en/docs/reference/foreachattribute) methods, and [`EcsSystem.OnDestroy`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#ondestroy) when removed or when the world is disposed. Everything runs synchronously within [`World.Update`](https://ecs.xgamedev.net/en/docs/reference/world#update) (or [`World.Update`](https://ecs.xgamedev.net/en/docs/reference/world#update-2) for systems in a [group](https://ecs.xgamedev.net/en/docs/reference/updateingroupattribute)): on the calling thread, or with [`WorldOptions.ParallelSystems`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#parallelsystems) on a thread-pool thread next to systems whose [access](https://ecs.xgamedev.net/en/docs/reference/systemaccess) does not conflict. ## Constructors ### `EcsSystem` ```csharp protected EcsSystem(); ``` ## Properties ### `Enabled` ```csharp public bool Enabled { get; set; } ``` Disabled systems are skipped by [`World.Update`](https://ecs.xgamedev.net/en/docs/reference/world#update) and [`World.Update`](https://ecs.xgamedev.net/en/docs/reference/world#update-2). Enabling a system clears its [`EcsSystem.Error`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#error). ### `Error` ```csharp public Exception Error { get; } ``` The exception that switched this system off under [`SystemErrorPolicy.Disable`](https://ecs.xgamedev.net/en/docs/reference/systemerrorpolicy#disable), until it is enabled again; null otherwise. ### `LastRunTick` ```csharp public ulong LastRunTick { get; } ``` The world's [`World.ChangeTick`](https://ecs.xgamedev.net/en/docs/reference/world#changetick) when this system last ran (0 before its first run): its `[Changed]` methods select rows written after that tick, so not their own writes of that run. ### `Stats` ```csharp public SystemStats Stats { get; } ``` Run count and time of this system; recorded only with [`WorldOptions.MeasureSystems`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#measuresystems). ### `UpdateInterval` ```csharp public virtual int UpdateInterval { get; } ``` Run every N-th world update (1 = every update); see [`EcsSystem.UpdatePhase`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#updatephase). ### `UpdatePhase` ```csharp public virtual int UpdatePhase { get; } ``` Which of the [`EcsSystem.UpdateInterval`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#updateinterval) updates the system runs on (0 to interval - 1): systems with the same interval and different phases spread their work over the updates instead of all running on the same one. ### `World` ```csharp public World World { get; } ``` The world this system belongs to (set before [`EcsSystem.OnCreate`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#oncreate)). ## Methods ### `OnCreate` ```csharp protected virtual void OnCreate(); ``` Called once when the system is added to a world. ### `OnDestroy` ```csharp protected virtual void OnDestroy(); ``` Called once when the system is removed or the world is disposed. ### `OnUpdate` ```csharp protected virtual void OnUpdate(); ``` Called every update before the system's [ForEach] methods. --- # Entity > Handle to an entity: id + version + world (16 bytes). The Entity struct of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/entity Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference/entity.md ```csharp public readonly struct Entity : IEquatable ``` Handle to an entity: id + version + world (16 bytes). Every access validates the version, so a handle to a destroyed entity never touches the entity that reused its id: questions ([`Entity.IsAlive`](https://ecs.xgamedev.net/en/docs/reference/entity#isalive), [`Entity.Has`](https://ecs.xgamedev.net/en/docs/reference/entity#has), [`Entity.TryGet`](https://ecs.xgamedev.net/en/docs/reference/entity#tryget), [`Entity.TryGetRef`](https://ecs.xgamedev.net/en/docs/reference/entity#trygetref)) answer false, accesses and changes ([`Entity.Get`](https://ecs.xgamedev.net/en/docs/reference/entity#get), [`Entity.Read`](https://ecs.xgamedev.net/en/docs/reference/entity#read), [`Entity.GetOrAdd`](https://ecs.xgamedev.net/en/docs/reference/entity#getoradd), `Set`, `Remove`) throw, and [`Entity.Destroy`](https://ecs.xgamedev.net/en/docs/reference/entity#destroy) does nothing. Safe to store and to compare. #### Remarks Refs returned by [`Entity.Get`](https://ecs.xgamedev.net/en/docs/reference/entity#get)/[`Entity.GetOrAdd`](https://ecs.xgamedev.net/en/docs/reference/entity#getoradd) point into the row of the entity's archetype table: use them immediately and never keep them across a structural change of that entity (it moves the row) or an `await`. ## Fields ### `Id` ```csharp public readonly EntityId Id; ``` The entity's identity (index and incarnation): what to store in a component or send elsewhere to refer to it ([`World.TryGetEntity`](https://ecs.xgamedev.net/en/docs/reference/world#trygetentity) turns it back into a handle). ## Properties ### `IsAlive` ```csharp public bool IsAlive { get; } ``` Whether this incarnation is alive. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `World` ```csharp public World World { get; } ``` The world owning the entity (null for `default`). ## Methods ### `AddRelation` ```csharp public Entity AddRelation(in T relation) where T : struct, IRelation; ``` Link the entity to `relation`'s target: append it to the entity's [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer) (added first if missing) and to the relation index. Returns the entity. O(1) amortized; structural only when the buffer is added. Throws if the entity is not alive. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) amortized ### `Clone` ```csharp public Entity Clone(); ``` A new entity of the same world with a copy of every component of this one (a [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer) gets a list of its own, indexes learn the copy, tracked components count as written now); throws if this entity is not alive. To create entities from a template, use a [`Prefab`](https://ecs.xgamedev.net/en/docs/reference/prefab). O(components). Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(c) ### `Describe` ```csharp public ComponentValue[] Describe(); ``` Boxed copies of the entity's components, disabled ones marked; none when it is not alive. For diagnostics (the debugger shows the same): cold, allocates. O(components). Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(c) ### `Destroy` ```csharp public void Destroy(); ``` Destroy the entity; a destroyed handle is ignored. O(components). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(c) ### `Disable` ```csharp public bool Disable() where T : struct, IComponent; ``` Disable component `T`: the entity keeps its value but lacks it (queries, `Has`, `Get`) until [`Entity.Enable`](https://ecs.xgamedev.net/en/docs/reference/entity#enable), and gets the tag [`Disabled`](https://ecs.xgamedev.net/en/docs/reference/disabled). Counts as a removal for `[Removed]`; an indexed component leaves its index. Returns false when the entity lacks `T` (or has it disabled already); throws if it is not alive. O(1); the first disable in a table moves the row once (to the table with the tag's column). Not for an [`ICleanupComponent`](https://ecs.xgamedev.net/en/docs/reference/icleanupcomponent) (it must stay to be released) or [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) (a parent's destruction must find its children): those throw. Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1); the first disable in a table moves the row once ### `Enable` ```csharp public bool Enable() where T : struct, IComponent; ``` Give back a component disabled by [`Entity.Disable`](https://ecs.xgamedev.net/en/docs/reference/entity#disable), with the value it kept (`Set` would replace it). Counts as a write of a tracked component; an indexed one rejoins its index. Returns false when `T` is not disabled; throws if the entity is not alive. O(1). Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1); the first disable in a table moves the row once ### `Equals` ```csharp public bool Equals(Entity other); public override bool Equals(object obj); ``` Whether both handles name the same entity of the same world: id and version. O(1). ### `Get` ```csharp public ref T Get() where T : struct, IComponent; ``` Ref to component `T`; throws if the entity does not have it or is not alive. Counts as a write of a tracked component ([`ITrackChanges`](https://ecs.xgamedev.net/en/docs/reference/itrackchanges)). O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `GetHashCode` ```csharp public override int GetHashCode(); ``` A hash of the id and version. O(1). ### `GetOrAdd` ```csharp public ref T GetOrAdd() where T : struct, IComponent; ``` Ref to component `T`, adding it (default) first if missing. Counts as a write of a tracked component. O(1); when missing, O(1) if the entity's table has a column for it (the row only gets its presence bit back), else O(c) amortized: the row moves to the table with the column (c components copied). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1); when missing, O(1) if the table has a column for `T`, else O(c) amortized ### `Has` ```csharp public bool Has() where T : struct, IComponent; ``` Whether the entity has component `T`; false for a destroyed or default handle. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `entity.Has()`: O(1) - `entity.Has()`: O(n) ### `Has` ```csharp public bool Has() where T1 : struct, IComponent where T2 : struct, IComponent; public bool Has() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public bool Has() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public bool Has() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public bool Has() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public bool Has() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public bool Has() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public bool Has() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` Whether the entity has all of `T1, T2`; false for a destroyed or default handle. O(2). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `entity.Has()`: O(1) - `entity.Has()`: O(n) ### `HasRelation` ```csharp public bool HasRelation(EntityId target) where T : struct, IRelation; ``` Whether the entity links to `target` with a `T`. O(links of the entity). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(L) ### `IsDisabled` ```csharp public bool IsDisabled() where T : struct, IComponent; ``` Whether component `T` is disabled ([`Entity.Disable`](https://ecs.xgamedev.net/en/docs/reference/entity#disable)): the entity has [`Disabled`](https://ecs.xgamedev.net/en/docs/reference/disabled). O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Read` ```csharp public ref readonly T Read() where T : struct, IComponent; ``` Read-only ref to component `T`; throws if the entity does not have it or is not alive. Not a write: a tracked component ([`ITrackChanges`](https://ecs.xgamedev.net/en/docs/reference/itrackchanges)) is not stamped. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Remove` ```csharp public Entity Remove() where T1 : struct, IComponent; public Entity Remove() where T1 : struct, IComponent where T2 : struct, IComponent; public Entity Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public Entity Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public Entity Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public Entity Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public Entity Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public Entity Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public Entity Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Remove 2 components; missing components are ignored. The entity keeps its row (no move). Returns the entity for chaining. O(2). Owner thread only (see docs/content/guide/threading.md). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(n) ### `RemoveRelation` ```csharp public int RemoveRelation(EntityId target) where T : struct, IRelation; ``` Drop the entity's links of kind `T` to `target` (every element with that target). Returns how many went. O(links of the entity). Throws if the entity is not alive. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(L) ### `Run` ```csharp public bool Run(ref TJob job) where T1 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job) where T1 : struct, IComponent where T2 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Run `job` on this entity when it has all of `T1, T2`, with the refs `World.ForEachEntity` would give it: true when the job ran, false when the entity lacks a component or is not alive. The components the job writes (`IForEachEntity.Writes`) count as written; a structural change the job makes takes effect at once, and those writes are carried over to the entity's new row (also when the job throws). A job implementing [`INoStructuralChanges`](https://ecs.xgamedev.net/en/docs/reference/inostructuralchanges) skips that bookkeeping. O(1), allocation-free. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `entity.Run(ref job)`: O(n), plus O(1) per filter component - `Run(ref job, filter)`: O(n), plus O(1) per filter component ### `Run` ```csharp public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where T2 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public bool Run(ref TJob job, in QueryFilter filter) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. [`Entity.Run`](https://ecs.xgamedev.net/en/docs/reference/entity#run) when the entity also passes `filter`, tested as a query tests a row (`Without`, `WithAny`, `Changed`, groups): false, without running the job, when it does not. O(components the filter names). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `entity.Run(ref job)`: O(n), plus O(1) per filter component - `Run(ref job, filter)`: O(n), plus O(1) per filter component ### `Set` ```csharp public Entity Set(in T1 c1) where T1 : struct, IComponent; public Entity Set(in T1 c1, in T2 c2) where T1 : struct, IComponent where T2 : struct, IComponent; public Entity Set(in T1 c1, in T2 c2, in T3 c3) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public Entity Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public Entity Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public Entity Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public Entity Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public Entity Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7, in T8 c8) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public Entity Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7, in T8 c8, in T9 c9) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Add or overwrite 2 components with the given values, with at most one row copy. Returns the entity for chaining. O(2) amortized. Owner thread only (see docs/content/guide/threading.md). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(n), or O(c) amortized when it moves ### `ToString` ```csharp public override string ToString(); ``` `Entity 3v1`: the id's index and version. ### `TryGet` ```csharp public bool TryGet(out T value) where T : struct, IComponent; ``` Copy of component `T` if the entity has it; false when it does not or is not alive. Not a write. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `TryGetRef` ```csharp public ref T TryGetRef(out bool found) where T : struct, IComponent; ``` Ref to component `T` when the entity has it (`found`), else a null ref: check `found` before using it. False when the entity is not alive. Counts as a write of a tracked component when found. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ## Operators ### `operator !=` ```csharp public static bool operator !=(Entity left, Entity right); ``` Whether the handles name different entities (or worlds). O(1). ### `operator ==` ```csharp public static bool operator ==(Entity left, Entity right); ``` Whether both handles name the same entity of the same world: id and version. O(1). ### `operator implicit` ```csharp public static implicit operator EntityId(Entity entity); ``` The handle's [`Entity.Id`](https://ecs.xgamedev.net/en/docs/reference/entity#id): store ids, not handles, in components. --- # EntityId > The identity of an entity: its index and the incarnation of that index (8 bytes, unmanaged). URL: https://ecs.xgamedev.net/en/docs/reference/entityid Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/entityid.md ```csharp public readonly struct EntityId : IEquatable ``` The identity of an entity: its index and the incarnation of that index (8 bytes, unmanaged). Store it wherever an entity is referred to from data (a relation, a target, an owner, a message): a component holding only unmanaged values keeps an unmanaged column, which is pinned, copied as a block and never scanned by the GC, and serializes as raw bytes. Turn it back into a handle with [`World.TryGetEntity`](https://ecs.xgamedev.net/en/docs/reference/world#trygetentity); a handle converts to its id implicitly. `default` is [`EntityId.Null`](https://ecs.xgamedev.net/en/docs/reference/entityid#null), which no entity has. ## Constructors ### `EntityId` ```csharp public EntityId(int index, int version); ``` The id of entity `index`, incarnation `version`. ## Fields ### `Index` ```csharp public readonly int Index; ``` Entity index (dense, recycled after destruction). ### `Version` ```csharp public readonly int Version; ``` Incarnation of [`EntityId.Index`](https://ecs.xgamedev.net/en/docs/reference/entityid#index); starts at 1 and grows each time an entity with the index is destroyed. ## Properties ### `IsNull` ```csharp public bool IsNull { get; } ``` Whether this is [`EntityId.Null`](https://ecs.xgamedev.net/en/docs/reference/entityid#null). ### `Null` ```csharp public static EntityId Null { get; } ``` The id no entity has (`default`): an empty reference. ## Methods ### `Equals` ```csharp public bool Equals(EntityId other); public override bool Equals(object obj); ``` ### `GetHashCode` ```csharp public override int GetHashCode(); ``` ### `ToString` ```csharp public override string ToString(); ``` ## Operators ### `operator !=` ```csharp public static bool operator !=(EntityId left, EntityId right); ``` Different ids name different entities or incarnations. ### `operator ==` ```csharp public static bool operator ==(EntityId left, EntityId right); ``` Equal ids name the same incarnation of the same entity. --- # EntityIdField > An EntityId field of value (see SavedTypes.EntityIds). The EntityIdField delegate of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/entityidfield Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/entityidfield.md ```csharp public delegate ref EntityId EntityIdField(ref T value); ``` An [`EntityId`](https://ecs.xgamedev.net/en/docs/reference/entityid) field of `value` (see `SavedTypes.EntityIds`). ## Constructors ### `EntityIdField` ```csharp public EntityIdField(object @object, nint method); ``` ## Methods ### `BeginInvoke` ```csharp public virtual IAsyncResult BeginInvoke(ref T value, AsyncCallback callback, object @object); ``` ### `EndInvoke` ```csharp public virtual ref EntityId EndInvoke(ref T value, IAsyncResult result); ``` --- # EntitySpan > The entities of one run of rows in a batch job: element i is the entity whose components are element i of the run's spans. URL: https://ecs.xgamedev.net/en/docs/reference/entityspan Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/entityspan.md ```csharp public readonly ref struct EntitySpan ``` The entities of one run of rows in a batch job: element `i` is the entity whose components are element `i` of the run's spans. A handle is built only when indexed, so a batch that needs the entity of a few rows reads only those rows' ids. Valid for the call it is passed to (a ref struct, like the spans). ## Properties ### `Ids` ```csharp public ReadOnlySpan Ids { get; } ``` The ids of the run's entities, read straight from the table (no copy): to store or send them. ### `Length` ```csharp public int Length { get; } ``` Number of entities (the length of the run's spans). ## Indexers ### `this[]` ```csharp public Entity this[int index] { get; } ``` The entity of row `index` of the run. O(1): one 8-byte load. --- # ForEachAttribute > Runs a method of an EcsSystem (or a static method of any other type, through a generated entry point) for every entity matching its component parameters… URL: https://ecs.xgamedev.net/en/docs/reference/foreachattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/foreachattribute.md ```csharp public sealed class ForEachAttribute : Attribute ``` Runs a method of an [`EcsSystem`](https://ecs.xgamedev.net/en/docs/reference/ecssystem) (or a static method of any other type, through a generated entry point) for every entity matching its component parameters (and the [`WithAttribute`](https://ecs.xgamedev.net/en/docs/reference/withattribute) / [`WithoutAttribute`](https://ecs.xgamedev.net/en/docs/reference/withoutattribute) / [`WithAnyAttribute`](https://ecs.xgamedev.net/en/docs/reference/withanyattribute) filters), each update, after [`EcsSystem.OnUpdate`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#onupdate), in declaration order. Parameters: 1..9 components (`ref` to write, `in` to read; or `Span` / `ReadOnlySpan` for a batch method that receives runs of rows), singletons (`ref` / `in`), and optionally [`Entity`](https://ecs.xgamedev.net/en/docs/reference/entity) and [`World`](https://ecs.xgamedev.net/en/docs/reference/world). Static and instance methods are supported. ```csharp public class MovementSystem : EcsSystem { [ForEach, Without] static void Move(ref Position p, in Velocity v) { p.X += v.X; p.Y += v.Y; } } ``` EasyEcs.Generator compiles it to a struct job ([`IForEach`](https://ecs.xgamedev.net/en/docs/reference/iforeach), [`IForEachEntity`](https://ecs.xgamedev.net/en/docs/reference/iforeachentity) or [`IForEachBatch`](https://ecs.xgamedev.net/en/docs/reference/iforeachbatch)): no delegate, no allocation, inlined. ## Constructors ### `ForEachAttribute` ```csharp public ForEachAttribute(); ``` ## Properties ### `Parallel` ```csharp public bool Parallel { get; init; } ``` Run chunks of the matching rows on several threads (`World.ForEachParallel`). The method must make no structural change, run per entity and write no singleton (EECS010); it pays off for heavy per-row work over tens of thousands of rows. Default false. --- # ICleanupComponent > Marks a component that outlives the destruction of its entity: destroying an entity holding one removes its other components and adds the Destroyed tag… URL: https://ecs.xgamedev.net/en/docs/reference/icleanupcomponent Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/icleanupcomponent.md ```csharp public interface ICleanupComponent : IComponent ``` Marks a component that outlives the destruction of its entity: destroying an entity holding one removes its other components and adds the [`Destroyed`](https://ecs.xgamedev.net/en/docs/reference/destroyed) tag instead of freeing it, so a system can release what the component stands for (a socket, a reservation, a slot in another service) and then remove it. Removing the entity's last cleanup component frees it. Use it for resources outside the world that must be released exactly once. --- # IComponent > Marks a struct as component data. The IComponent interface of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/icomponent Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/icomponent.md ```csharp public interface IComponent ``` Marks a struct as component data. Components are plain data stored in archetype tables, one column per type and one row per entity; keep them small (ideally a few fields, well under a 64-byte cache line) and split rarely-used data into separate components so iteration only loads what it touches. --- # IForEach > Struct callback for World.ForEach. The IForEach interface of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/iforeach Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/iforeach.md ```csharp public interface IForEach where T1 : struct, IComponent public interface IForEach where T1 : struct, IComponent where T2 : struct, IComponent public interface IForEach where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent public interface IForEach where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent public interface IForEach where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent public interface IForEach where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent public interface IForEach where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent public interface IForEach where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent public interface IForEach where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent ``` Struct callback for `World.ForEach`. Being a struct-constrained generic, calls are devirtualized and usually inlined by the JIT: no delegate, no closure, no allocation. `[ForEach]` methods compile to this. One type per number of components, 1 to 9 (generated from one template); the members below are those of each, shown for `IForEach`. ## Properties ### `Writes` ```csharp static virtual int Writes { get; } ``` Components the job writes through its refs: bit k - 1 for component k (default: all). When the job changes the archetype of the entity it visits, ForEach carries those components over from the row the refs point into to the entity's new row after the job returns. Generated jobs set only their `ref` parameters. ## Methods ### `Execute` ```csharp void Execute(ref T1 c1); ``` One matching entity: its components, by reference (`ref` writes them in place). --- # IForEachBatch > Struct callback for World.ForEachBatch: receives whole runs of rows as spans, one per component, so the job can process them with SIMD… URL: https://ecs.xgamedev.net/en/docs/reference/iforeachbatch Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/iforeachbatch.md ```csharp public interface IForEachBatch where T1 : struct, IComponent public interface IForEachBatch where T1 : struct, IComponent where T2 : struct, IComponent public interface IForEachBatch where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent public interface IForEachBatch where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent public interface IForEachBatch where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent public interface IForEachBatch where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent public interface IForEachBatch where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent public interface IForEachBatch where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent public interface IForEachBatch where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent ``` Struct callback for `World.ForEachBatch`: receives whole runs of rows as spans, one per component, so the job can process them with SIMD (`System.Numerics.Vector`, `MemoryMarshal.Cast`), and their entities (built only when indexed). `[ForEach]` methods taking `Span` / `ReadOnlySpan` compile to this. One type per number of components, 1 to 9 (generated from one template); the members below are those of each, shown for `IForEachBatch`. ## Properties ### `Writes` ```csharp static virtual int Writes { get; } ``` Components the job writes through its refs: bit k - 1 for component k (default: all). When the job changes the archetype of the entity it visits, ForEach carries those components over from the row the refs point into to the entity's new row after the job returns. Generated jobs set only their `ref` parameters. ## Methods ### `Execute` ```csharp void Execute(EntitySpan entities, Span c1); ``` One run of consecutive rows of one archetype: element i of `entities` and of every span belongs to the same entity. --- # IForEachEntity > Like IForEach but also receives the Entity handle, built from the archetype's entity rows (id and version side by side) without a per-entity lookup. URL: https://ecs.xgamedev.net/en/docs/reference/iforeachentity Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/iforeachentity.md ```csharp public interface IForEachEntity where T1 : struct, IComponent public interface IForEachEntity where T1 : struct, IComponent where T2 : struct, IComponent public interface IForEachEntity where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent public interface IForEachEntity where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent public interface IForEachEntity where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent public interface IForEachEntity where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent public interface IForEachEntity where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent public interface IForEachEntity where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent public interface IForEachEntity where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent ``` Like [`IForEach`](https://ecs.xgamedev.net/en/docs/reference/iforeach) but also receives the [`Entity`](https://ecs.xgamedev.net/en/docs/reference/entity) handle, built from the archetype's entity rows (id and version side by side) without a per-entity lookup. `[ForEach]` methods taking an [`Entity`](https://ecs.xgamedev.net/en/docs/reference/entity) compile to this. One type per number of components, 1 to 9 (generated from one template); the members below are those of each, shown for `IForEachEntity`. ## Properties ### `Writes` ```csharp static virtual int Writes { get; } ``` Components the job writes through its refs: bit k - 1 for component k (default: all). When the job changes the archetype of the entity it visits, ForEach carries those components over from the row the refs point into to the entity's new row after the job returns. Generated jobs set only their `ref` parameters. ## Methods ### `Execute` ```csharp void Execute(Entity entity, ref T1 c1); ``` One matching entity: its handle and its components, by reference. --- # IGroup > Marks a component whose value splits tables: in a world that called World.GroupBy, entities with different IGroup.Groups live in different tables… URL: https://ecs.xgamedev.net/en/docs/reference/igroup Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/igroup.md ```csharp public interface IGroup ``` Marks a component whose value splits tables: in a world that called [`World.GroupBy`](https://ecs.xgamedev.net/en/docs/reference/world#groupby), entities with different [`IGroup.Group`](https://ecs.xgamedev.net/en/docs/reference/igroup#group)s live in different tables, so a query of one group ([`QueryFilter.InGroup`](https://ecs.xgamedev.net/en/docs/reference/queryfilter#ingroup)) walks only its own rows, contiguous in memory (a zone, a map, a match, a team). Writing a new value with `Set` moves the entity to its group's table, so a grouped component is never written through a `ref` (EECS015), like an indexed one. ## Properties ### `Group` ```csharp int Group { get; } ``` The group the entity belongs to. --- # IGroupWith > A system group whose [ForEach] methods visit only entities with T, as WithAttribute on the group would. URL: https://ecs.xgamedev.net/en/docs/reference/igroupwith Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference/igroupwith.md ```csharp public interface IGroupWith : ISystemGroup where T : struct, IComponent ``` A system group whose [ForEach] methods visit only entities with `T`, as [`WithAttribute`](https://ecs.xgamedev.net/en/docs/reference/withattribute) on the group would. An interface can name its own type parameter where an attribute cannot, so a framework's generic group interface carries the filter for every group that implements it: `interface IActor : IGroupWith>`, then `struct Map : IActor` filters its systems to `In`. Read by the generator: no cost at run time. --- # IGroupWithout > A system group whose [ForEach] methods skip entities with T, as WithoutAttribute on the group would (see IGroupWith). URL: https://ecs.xgamedev.net/en/docs/reference/igroupwithout Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference/igroupwithout.md ```csharp public interface IGroupWithout : ISystemGroup where T : struct, IComponent ``` A system group whose [ForEach] methods skip entities with `T`, as [`WithoutAttribute`](https://ecs.xgamedev.net/en/docs/reference/withoutattribute) on the group would (see [`IGroupWith`](https://ecs.xgamedev.net/en/docs/reference/igroupwith)). --- # IIndexed, IIndexed > What every IIndexed is, so a component type is known to be indexed without reflection (a type test the JIT folds). URL: https://ecs.xgamedev.net/en/docs/reference/iindexed Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/iindexed.md ```csharp public interface IIndexed public interface IIndexed : IIndexed where TKey : IEquatable ``` What every [`IIndexed`](https://ecs.xgamedev.net/en/docs/reference/iindexed) is, so a component type is known to be indexed without reflection (a type test the JIT folds). Implement [`IIndexed`](https://ecs.xgamedev.net/en/docs/reference/iindexed), not this. --- # INoStructuralChanges > Marks a ForEach job that makes no structural change (no create/destroy/add/remove/set on any entity of the world it iterates). URL: https://ecs.xgamedev.net/en/docs/reference/inostructuralchanges Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/inostructuralchanges.md ```csharp public interface INoStructuralChanges ``` Marks a `ForEach` job that makes no structural change (no create/destroy/add/remove/set on any entity of the world it iterates). ForEach then walks tables with no per-entity bookkeeping. The source generator adds it to `[ForEach]` methods that are static, take no [`World`](https://ecs.xgamedev.net/en/docs/reference/world) and use their [`Entity`](https://ecs.xgamedev.net/en/docs/reference/entity) parameter (if any) only to read; implement it by hand only when the job honors the contract. --- # IRelation > An element of a DynamicBuffer that links its entity to IRelation.Target… URL: https://ecs.xgamedev.net/en/docs/reference/irelation Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/irelation.md ```csharp public interface IRelation ``` An element of a [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer) that links its entity to [`IRelation.Target`](https://ecs.xgamedev.net/en/docs/reference/irelation#target): an entity holds any number of links of one kind (the members of a party, the items a merchant offers, the units a buff applies to), and [`World.Relations`](https://ecs.xgamedev.net/en/docs/reference/world#relations) finds the entities linking to a target. Links are written with [`Entity.AddRelation`](https://ecs.xgamedev.net/en/docs/reference/entity#addrelation) / [`Entity.RemoveRelation`](https://ecs.xgamedev.net/en/docs/reference/entity#removerelation) (or `Set` of a whole buffer), so the index follows; read them with `Read>()` or an `in` parameter. The analyzer reports writes through a `ref` (EECS015), as for any indexed component. ## Properties ### `Target` ```csharp EntityId Target { get; } ``` The entity the link points at. --- # ISingletonComponent > Marks a struct as a world singleton: exactly one value per world (clock, configuration, shared state). URL: https://ecs.xgamedev.net/en/docs/reference/isingletoncomponent Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/isingletoncomponent.md ```csharp public interface ISingletonComponent ``` Marks a struct as a world singleton: exactly one value per world (clock, configuration, shared state). --- # ISystemGroup > Marker of a system group: systems marked UpdateInGroupAttribute run together when World.Update is called… URL: https://ecs.xgamedev.net/en/docs/reference/isystemgroup Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference/isystemgroup.md ```csharp public interface ISystemGroup ``` Marker of a system group: systems marked [`UpdateInGroupAttribute`](https://ecs.xgamedev.net/en/docs/reference/updateingroupattribute) run together when [`World.Update`](https://ecs.xgamedev.net/en/docs/reference/world#update-2) is called, independently of the default group run by [`World.Update`](https://ecs.xgamedev.net/en/docs/reference/world#update). Use groups for different cadences (a fixed-rate simulation tick vs. work that runs whenever input arrives). ```csharp public struct NetworkGroup : ISystemGroup; [UpdateInGroup] public class ReceiveSystem : EcsSystem { ... } world.Update(); // whenever packets arrive world.Update(); // fixed tick: default group ``` A group may carry [`WithAttribute`](https://ecs.xgamedev.net/en/docs/reference/withattribute), [`WithoutAttribute`](https://ecs.xgamedev.net/en/docs/reference/withoutattribute) and [`WithAnyAttribute`](https://ecs.xgamedev.net/en/docs/reference/withanyattribute) filters: the generator adds them to every [ForEach] method of its systems (`[Without] public struct Gameplay : ISystemGroup;` keeps inactive entities out of the whole group), and so may the interfaces it implements: [`IGroupWith`](https://ecs.xgamedev.net/en/docs/reference/igroupwith), [`IGroupWithout`](https://ecs.xgamedev.net/en/docs/reference/igroupwithout). Queries a system makes in OnUpdate are its own. --- # ITrackChanges > Marks a component whose changes are tracked: every row records the world's World.ChangeTick of its last write… URL: https://ecs.xgamedev.net/en/docs/reference/itrackchanges Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/itrackchanges.md ```csharp public interface ITrackChanges ``` Marks a component whose changes are tracked: every row records the world's [`World.ChangeTick`](https://ecs.xgamedev.net/en/docs/reference/world#changetick) of its last write, and `[Changed]` / `QueryFilter.Changed(since)` select the rows written since a system last ran. A write is any `ref` access: `ref` parameters of `[ForEach]` methods and jobs, `Query` items, `Entity.Get` / `Add` / `GetOrAdd` / `Set`, and creating the entity or adding the component. Costs 8 bytes per row and one store per write; untracked components pay nothing. --- # Maybe > An optional component of the entity a [ForEach] method visits: static void Regen(ref Health h, Maybe buff) visits every entity with Health… URL: https://ecs.xgamedev.net/en/docs/reference/maybe Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/maybe.md ```csharp public readonly ref struct Maybe where T : struct, IComponent ``` An optional component of the entity a `[ForEach]` method visits: `static void Regen(ref Health h, Maybe buff)` visits every entity with Health, and [`Maybe.HasValue`](https://ecs.xgamedev.net/en/docs/reference/maybe#hasvalue) tells whether this one also has a Buff. One method instead of a With and a Without variant when the optional part is small. A method that changes no structure finds the column once per run of rows and tests a presence bit per row; one that changes structure looks the component up through each entity. Split the method in two with `[With]` / `[Without]` in the hottest loops (no test per row). A method that only reads [`Maybe.Value`](https://ecs.xgamedev.net/en/docs/reference/maybe#value) reads `T`; one that writes through it (assigns, increments, passes it by `ref`, calls a method on it) writes `T`, and a tracked component is stamped when present. Valid for the call it is passed to (a ref struct). ## Constructors ### `Maybe` ```csharp public Maybe(ref T value); ``` Wraps `value`, a null ref when the entity lacks the component. ## Properties ### `HasValue` ```csharp public bool HasValue { get; } ``` Whether the entity has the component. ### `Value` ```csharp public ref T Value { get; } ``` The component by `ref`; throws when the entity lacks it (check [`Maybe.HasValue`](https://ecs.xgamedev.net/en/docs/reference/maybe#hasvalue)). --- # OrderedIndexExtensions > Ordered walks of a value index whose key is comparable (a score, a deadline, a level)… URL: https://ecs.xgamedev.net/en/docs/reference/orderedindexextensions Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/orderedindexextensions.md ```csharp public static class OrderedIndexExtensions ``` Ordered walks of a value index whose key is comparable (a score, a deadline, a level): ranges and sorted iteration for leaderboards, timers and matchmaking brackets. The first walk sorts the keys once; the index then keeps them sorted as keys appear and disappear (O(log keys) plus a block move each). ## Methods ### `Ascending` ```csharp public static ValueIndex.Ordered Ascending(this ValueIndex index) where T : struct, IComponent, IIndexed where TKey : IEquatable, IComparable; ``` Every indexed entity by ascending key. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(keys log keys) for the first walk, then O(1) per entity ### `Descending` ```csharp public static ValueIndex.Ordered Descending(this ValueIndex index) where T : struct, IComponent, IIndexed where TKey : IEquatable, IComparable; ``` Every indexed entity by descending key (the top of a leaderboard first). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(keys log keys) for the first walk, then O(1) per entity ### `Range` ```csharp public static ValueIndex.Ordered Range(this ValueIndex index, TKey min, TKey max) where T : struct, IComponent, IIndexed where TKey : IEquatable, IComparable; ``` The entities whose key is between `min` and `max` (inclusive), by ascending key. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(keys log keys) for the first walk, then O(log keys) to find `min` and O(1) per entity ### `RangeDescending` ```csharp public static ValueIndex.Ordered RangeDescending(this ValueIndex index, TKey min, TKey max) where T : struct, IComponent, IIndexed where TKey : IEquatable, IComparable; ``` The entities whose key is between `min` and `max` (inclusive), by descending key. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(keys log keys) for the first walk, then O(log keys) to find `min` and O(1) per entity ## Extension members ### `Ascending` ```csharp extension(ValueIndex index) public ValueIndex.Ordered Ascending(); ``` Every indexed entity by ascending key. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(keys log keys) for the first walk, then O(1) per entity ### `Descending` ```csharp extension(ValueIndex index) public ValueIndex.Ordered Descending(); ``` Every indexed entity by descending key (the top of a leaderboard first). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(keys log keys) for the first walk, then O(1) per entity ### `Range` ```csharp extension(ValueIndex index) public ValueIndex.Ordered Range(TKey min, TKey max); ``` The entities whose key is between `min` and `max` (inclusive), by ascending key. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(keys log keys) for the first walk, then O(log keys) to find `min` and O(1) per entity ### `RangeDescending` ```csharp extension(ValueIndex index) public ValueIndex.Ordered RangeDescending(TKey min, TKey max); ``` The entities whose key is between `min` and `max` (inclusive), by descending key. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(keys log keys) for the first walk, then O(log keys) to find `min` and O(1) per entity --- # Prefab > A recipe for entities: a set of component values that belongs to no world, so no query ever sees it. URL: https://ecs.xgamedev.net/en/docs/reference/prefab Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/prefab.md ```csharp public sealed class Prefab ``` A recipe for entities: a set of component values that belongs to no world, so no query ever sees it. [`World.Instantiate`](https://ecs.xgamedev.net/en/docs/reference/world#instantiate) creates an entity with a copy of every value, in any world. Build it once (from code or configuration) and keep it; one prefab may serve worlds on several threads as long as nobody changes it meanwhile. A prefab may have members ([`Prefab.AddMember`](https://ecs.xgamedev.net/en/docs/reference/prefab#addmember)): a boss with its minions and its mount. Instantiating any of them creates the whole group, and an [`EntityId`](https://ecs.xgamedev.net/en/docs/reference/entityid) field that names a member ([`Prefab.Id`](https://ecs.xgamedev.net/en/docs/reference/prefab#id), for example `new ChildOf(boss.Id)`) names that member's new entity, any other is [`EntityId.Null`](https://ecs.xgamedev.net/en/docs/reference/entityid#null): ids in a prefab name members only (an id of a world's entity may equal a member's). An [`Entity`](https://ecs.xgamedev.net/en/docs/reference/entity) field is copied as it is: set relations to a world's entities after instantiating. ## Constructors ### `Prefab` ```csharp public Prefab(); ``` An empty recipe. O(1); allocates its private store once. ### `Prefab` ```csharp public Prefab(Prefab basePrefab); ``` A prefab with a copy of every value of `basePrefab` (and of its members), to change on its own: a variant of a configured NPC. Later changes of either prefab do not reach the other (a copy, no inheritance). O(components). ## Properties ### `Id` ```csharp public EntityId Id { get; } ``` The id that names this member in the components of the group (rewritten on every instance). ## Methods ### `AddMember` ```csharp public Prefab AddMember(); ``` A new member of this prefab's group, without components: instantiating the prefab or any member creates every member. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Has` ```csharp public bool Has() where T : struct, IComponent; ``` Whether the prefab has component `T`. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Read` ```csharp public ref readonly T Read() where T : struct, IComponent; ``` The prefab's value of `T`; throws if it has none (change it with `Set`). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Remove` ```csharp public Prefab Remove() where T1 : struct, IComponent; public Prefab Remove() where T1 : struct, IComponent where T2 : struct, IComponent; public Prefab Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public Prefab Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public Prefab Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public Prefab Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public Prefab Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public Prefab Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public Prefab Remove() where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Drop 2 components from the recipe; missing components are ignored. Returns this prefab. O(2). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(n) ### `Set` ```csharp public Prefab Set(in T1 c1) where T1 : struct, IComponent; public Prefab Set(in T1 c1, in T2 c2) where T1 : struct, IComponent where T2 : struct, IComponent; public Prefab Set(in T1 c1, in T2 c2, in T3 c3) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public Prefab Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public Prefab Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public Prefab Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public Prefab Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public Prefab Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7, in T8 c8) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public Prefab Set(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7, in T8 c8, in T9 c9) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Add 2 components to the recipe, or replace their values. Returns this prefab (chain calls). O(2). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(n), or O(c) amortized when it gains a component ### `SetBuffer` ```csharp public Prefab SetBuffer(params ReadOnlySpan elements) where T : struct; ``` Gives the prefab a [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer) of `elements`, replacing the one it has: every instance gets a list of its own with these elements. Returns the prefab. O(n). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(n) --- # QueryEnumerator > Allocation-free query enumerator; safe under structural changes during iteration (same visiting rules as ForEach). URL: https://ecs.xgamedev.net/en/docs/reference/queryenumerator Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/queryenumerator.md ```csharp public ref struct QueryEnumerator where T1 : struct, IComponent public ref struct QueryEnumerator where T1 : struct, IComponent where T2 : struct, IComponent public ref struct QueryEnumerator where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent public ref struct QueryEnumerator where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent public ref struct QueryEnumerator where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent public ref struct QueryEnumerator where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent public ref struct QueryEnumerator where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent public ref struct QueryEnumerator where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent public ref struct QueryEnumerator where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent ``` Allocation-free query enumerator; safe under structural changes during iteration (same visiting rules as ForEach). A ref struct: it holds refs into the current table, so a loop over it cannot `await`. #### Remarks Every member the loop calls is inlined and the cold work is static (`QueryWalk`, by value in and out): the enumerator is never passed by reference, so its fields live in registers. One type per number of components, 1 to 9 (generated from one template); the members below are those of each, shown for `QueryEnumerator`. ## Properties ### `Current` ```csharp public readonly QueryItem Current { get; } ``` The current entity and its components. ## Methods ### `Dispose` ```csharp public void Dispose(); ``` Ends the walk early (`foreach` calls it); a walk that reaches the end ends by itself. ### `GetEnumerator` ```csharp public readonly QueryEnumerator GetEnumerator(); ``` The enumerator itself (`foreach` support, no allocation). ### `MoveNext` ```csharp public bool MoveNext(); ``` Move to the next matching entity. O(1) per row, plus the tables it steps over. --- # QueryFilter > Extra query constraints: components that must be present without being read (QueryFilter.With) or must be absent (QueryFilter.Without). URL: https://ecs.xgamedev.net/en/docs/reference/queryfilter Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/queryfilter.md ```csharp public readonly struct QueryFilter ``` Extra query constraints: components that must be present without being read ([`QueryFilter.With`](https://ecs.xgamedev.net/en/docs/reference/queryfilter#with)) or must be absent ([`QueryFilter.Without`](https://ecs.xgamedev.net/en/docs/reference/queryfilter#without)). Build once and keep it (e.g. in a static readonly field): ```csharp static readonly QueryFilter Alive = QueryFilter.Create().Without(); ``` ## Methods ### `Changed` ```csharp public QueryFilter Changed(ulong since) where T : struct, IComponent, ITrackChanges; ``` Require `T` and only rows whose `T` was written at or after change tick `since`: a [`World.ChangeTick`](https://ecs.xgamedev.net/en/docs/reference/world#changetick) read earlier (`[Changed]` methods select the rows written since their system last ran on their own). A filter has one tick: its `Changed` and `Removed` filters must name the same one. **Exceptions** - `ArgumentException`: An earlier `Changed` or `Removed` filter named another tick. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1); a pass skips tables, 4,096-row blocks and 64-row words written before `since` ### `Create` ```csharp public static QueryFilter Create(); ``` A filter that matches every entity with the queried components: the start of a chain (`Create().Without()`). O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `InGroup` ```csharp public QueryFilter InGroup(int group) where T : struct, IComponent, IGroup; ``` Require `T` with group `group`: only the tables of that group are walked ([`World.GroupBy`](https://ecs.xgamedev.net/en/docs/reference/world#groupby); in a world that does not group by `T`, every table holds group 0). One group per filter. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1); a pass walks only that group's tables ### `Removed` ```csharp public QueryFilter Removed(ulong since) where T : struct, IComponent, ITrackChanges; ``` Only entities that lost `T` at or after change tick `since` and have not got it back (`[Removed]` methods select the removals since their system last ran on their own). Removing a component keeps the entity's row, so the removal is a row like any other: its presence bit is clear and its change tick says when. Destroyed entities have no row and are not visited. A filter has one tick: its `Changed` and `Removed` filters must name the same one. **Exceptions** - `ArgumentException`: An earlier `Changed` or `Removed` filter named another tick. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): as `Changed` ### `Since` ```csharp public QueryFilter Since(ulong since); ``` The same filter with its [`QueryFilter.Changed`](https://ecs.xgamedev.net/en/docs/reference/queryfilter#changed) and [`QueryFilter.Removed`](https://ecs.xgamedev.net/en/docs/reference/queryfilter#removed) filters moved to tick `since`, without rebuilding it: a filter kept in a field, used again after each update. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `With` ```csharp public QueryFilter With() where T : struct, IComponent; ``` Require `T` to be present (not passed to the query callback). ### `WithAny` ```csharp public QueryFilter WithAny() where T : struct, IComponent; ``` Require at least one of the components named by `WithAny` calls: `WithAny().WithAny()` matches entities with Burning, Poisoned or both. ### `Without` ```csharp public QueryFilter Without() where T : struct, IComponent; ``` Require `T` to be absent. --- # QueryItem > One query result: the entity and refs into its row. The QueryItem struct of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/queryitem Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/queryitem.md ```csharp public readonly ref struct QueryItem where T1 : struct, IComponent public readonly ref struct QueryItem where T1 : struct, IComponent where T2 : struct, IComponent public readonly ref struct QueryItem where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent public readonly ref struct QueryItem where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent public readonly ref struct QueryItem where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent public readonly ref struct QueryItem where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent public readonly ref struct QueryItem where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent public readonly ref struct QueryItem where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent public readonly ref struct QueryItem where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent ``` One query result: the entity and refs into its row. Like every ref into ECS storage, the refs are valid until the next structural change; re-read through [`QueryItem.Entity`](https://ecs.xgamedev.net/en/docs/reference/queryitem#entity) after one. One type per number of components, 1 to 9 (generated from one template); the members below are those of each, shown for `QueryItem`. ## Properties ### `Component1` ```csharp public ref T1 Component1 { get; } ``` The current entity's T1, a reference into its row (the generator names it after the component: `item.Position`). ### `Entity` ```csharp public Entity Entity { get; } ``` Handle of the current entity. --- # RelationIndex > The links of relation T in one world, by target (World.Relations): which entities link to an entity, O(1) to start and O(1) per link. URL: https://ecs.xgamedev.net/en/docs/reference/relationindex Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/relationindex.md ```csharp public sealed class RelationIndex where T : struct, IRelation ``` The links of relation `T` in one world, by target ([`World.Relations`](https://ecs.xgamedev.net/en/docs/reference/world#relations)): which entities link to an entity, O(1) to start and O(1) per link. Kept current as links are written and as their entities are destroyed or lose the buffer; the first lookup (and the first after [`World.Restore`](https://ecs.xgamedev.net/en/docs/reference/world#restore)) indexes every buffer once. Links to a destroyed target stay findable by its id, which no later entity has. Owner thread only. Memory: one 20-byte link per element, recycled, and 8 bytes in its target's list. ## Methods ### `Count` ```csharp public int Count(EntityId target); ``` Number of links to `target`. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Find` ```csharp public RelationIndex.Sources Find(EntityId target); ``` The entities linking to `target`, once per link. Destroying entities during the loop is allowed, changing links is not. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1), then O(1) per link ### `WhenTargetDestroyed` ```csharp public RelationIndex WhenTargetDestroyed(TargetPolicy policy); ``` Decide what destroying an entity does to the links to it: [`TargetPolicy.Remove`](https://ecs.xgamedev.net/en/docs/reference/targetpolicy#remove) drops them (a party forgets a member that left the world), [`TargetPolicy.Destroy`](https://ecs.xgamedev.net/en/docs/reference/targetpolicy#destroy) destroys the linking entities (the buffs a caster applied end with the caster), [`TargetPolicy.Keep`](https://ecs.xgamedev.net/en/docs/reference/targetpolicy#keep) (the default) leaves them. Applied inside every destroy (the index is kept built); O(1) per destroyed entity, O(links of each source) per link. Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1); then O(1) per destroyed entity and O(L) per link --- # RelationIndex.Sources > Enumerates the entities linking to one target (foreach), once per link. URL: https://ecs.xgamedev.net/en/docs/reference/relationindex-sources Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/relationindex-sources.md ```csharp public ref struct Sources ``` Nested in [`RelationIndex`](https://ecs.xgamedev.net/en/docs/reference/relationindex). Enumerates the entities linking to one target (`foreach`), once per link. ## Properties ### `Current` ```csharp public readonly Entity Current { get; } ``` The current linking entity. ## Methods ### `GetEnumerator` ```csharp public readonly RelationIndex.Sources GetEnumerator(); ``` The enumerator itself (`foreach` support, no allocation). ### `MoveNext` ```csharp public bool MoveNext(); ``` Move to the next link. O(1) per link. --- # RemovedAttribute > The ForEachAttribute method visits only entities that lost T since its system last ran (EcsSystem.LastRunTick) and have not got it back… URL: https://ecs.xgamedev.net/en/docs/reference/removedattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/removedattribute.md ```csharp public sealed class RemovedAttribute : Attribute where T : struct, IComponent, ITrackChanges ``` The [`ForEachAttribute`](https://ecs.xgamedev.net/en/docs/reference/foreachattribute) method visits only entities that lost `T` since its system last ran ([`EcsSystem.LastRunTick`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#lastruntick)) and have not got it back: replication sends the removal, a cleanup releases what the component stood for. Removing a component keeps the entity's row, so the method can read the entity's other components; destroyed entities are not visited. `T` tracks changes ([`ITrackChanges`](https://ecs.xgamedev.net/en/docs/reference/itrackchanges)) and is not a parameter (the entity no longer has it, EECS016). ## Constructors ### `RemovedAttribute` ```csharp public RemovedAttribute(); ``` --- # SingletonRef > Handle to one world's singleton T. The SingletonRef struct of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/singletonref Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/singletonref.md ```csharp public readonly struct SingletonRef where T : struct, ISingletonComponent ``` Handle to one world's singleton `T`. The singleton's storage never moves, so the handle stays valid until the singleton is removed (a removed singleton is detached: writes no longer reach the world). ## Properties ### `Value` ```csharp public ref T Value { get; } ``` The singleton's value, by reference. --- # SystemAccess > The data a system reads and writes, declared once when the system is added. URL: https://ecs.xgamedev.net/en/docs/reference/systemaccess Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/systemaccess.md ```csharp public struct SystemAccess ``` The data a system reads and writes, declared once when the system is added. With [`WorldOptions.ParallelSystems`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#parallelsystems), systems with no order between them whose access does not conflict run at once: two systems conflict when one writes a component or singleton the other reads or writes, or when either [runs alone](https://ecs.xgamedev.net/en/docs/reference/systemaccess#runsalone). The generator declares it for every system with [[ForEach]](https://ecs.xgamedev.net/en/docs/reference/foreachattribute) methods: a `ref` parameter is a write, an `in` parameter a read. A system runs alone when it can reach the world beyond its parameters: an [`Entity`](https://ecs.xgamedev.net/en/docs/reference/entity) or [`World`](https://ecs.xgamedev.net/en/docs/reference/world) parameter, an instance `[ForEach]` method, an [`EcsSystem.OnUpdate`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#onupdate) override, or no `[ForEach]` method at all. ## Methods ### `Read` ```csharp public void Read() where T : struct, IComponent; ``` The system reads component `T`. ### `ReadSingleton` ```csharp public void ReadSingleton() where T : struct, ISingletonComponent; ``` The system reads singleton `T`. ### `RunsAlone` ```csharp public void RunsAlone(); ``` The system may touch anything (structural changes, any component): it never shares a stage. ### `Write` ```csharp public void Write() where T : struct, IComponent; ``` The system writes component `T`. ### `WriteSingleton` ```csharp public void WriteSingleton() where T : struct, ISingletonComponent; ``` The system writes singleton `T`. --- # SystemErrorPolicy > What an exception thrown by a system does (WorldOptions.SystemErrors). URL: https://ecs.xgamedev.net/en/docs/reference/systemerrorpolicy Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/systemerrorpolicy.md ```csharp public enum SystemErrorPolicy ``` What an exception thrown by a system does ([`WorldOptions.SystemErrors`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#systemerrors)). ## Fields ### `Disable` ```csharp Disable = 1; ``` Switch the failing system off ([`EcsSystem.Enabled`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#enabled) false), keep the exception in [`EcsSystem.Error`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#error) and go on with the update: a failure is data the application reads from [`World.Systems`](https://ecs.xgamedev.net/en/docs/reference/world#systems). ### `Throw` ```csharp Throw = 0; ``` Propagate out of the update (and out of [`World.Dispose`](https://ecs.xgamedev.net/en/docs/reference/world#dispose) for `OnDestroy`). --- # SystemList > The systems of a world, every group in execution order (default group first): foreach it, or read SystemList.Count. URL: https://ecs.xgamedev.net/en/docs/reference/systemlist Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/systemlist.md ```csharp public readonly struct SystemList ``` The systems of a world, every group in execution order (default group first): `foreach` it, or read [`SystemList.Count`](https://ecs.xgamedev.net/en/docs/reference/systemlist#count). A view, not a copy: allocation-free, it sees the systems registered when each group is reached. ## Properties ### `Count` ```csharp public int Count { get; } ``` Number of systems in every group. O(groups). ## Methods ### `GetEnumerator` ```csharp public SystemList.Enumerator GetEnumerator(); ``` The enumerator of `foreach`: every group's systems in execution order, allocation-free. --- # SystemList.Enumerator > Walks the groups and their systems. The SystemList.Enumerator struct of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/systemlist-enumerator Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/systemlist-enumerator.md ```csharp public struct Enumerator ``` Nested in [`SystemList`](https://ecs.xgamedev.net/en/docs/reference/systemlist). Walks the groups and their systems. ## Properties ### `Current` ```csharp public readonly EcsSystem Current { get; } ``` The current system. ## Methods ### `MoveNext` ```csharp public bool MoveNext(); ``` Move to the next system. O(1) amortized. --- # SystemStats > How often and how long a system ran (WorldOptions.MeasureSystems): EcsSystem.OnUpdate plus its [ForEach] methods, per run. URL: https://ecs.xgamedev.net/en/docs/reference/systemstats Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/systemstats.md ```csharp public readonly struct SystemStats ``` How often and how long a system ran ([`WorldOptions.MeasureSystems`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#measuresystems)): [`EcsSystem.OnUpdate`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#onupdate) plus its `[ForEach]` methods, per run. Read it between updates; with [`WorldOptions.ParallelSystems`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#parallelsystems) each system records its own runs. ## Properties ### `Average` ```csharp public TimeSpan Average { get; } ``` Average time per run (zero before the first). ### `Last` ```csharp public TimeSpan Last { get; } ``` Time of the latest run. ### `Runs` ```csharp public long Runs { get; } ``` Runs measured so far. ### `Total` ```csharp public TimeSpan Total { get; } ``` Time of all measured runs. --- # TableInfo > A table: the entities with one set of component columns (World.Describe). URL: https://ecs.xgamedev.net/en/docs/reference/tableinfo Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/tableinfo.md ```csharp public readonly struct TableInfo : IEquatable ``` A table: the entities with one set of component columns ([`World.Describe`](https://ecs.xgamedev.net/en/docs/reference/world#describe)). #### Parameters - `Columns`: The component columns, in bit order (change-tick and [`Disabled`](https://ecs.xgamedev.net/en/docs/reference/disabled) columns not listed). - `Entities`: Living entities. - `Rows`: Rows in use: the entities and the holes a query in progress left (closed when it ends). - `Capacity`: Rows allocated. - `Bytes`: Memory of the rows allocated: columns, change ticks, presence bits and entity slots (not the objects managed components reference). ## Constructors ### `TableInfo` ```csharp public TableInfo(ColumnInfo[] Columns, int Entities, int Rows, int Capacity, long Bytes); ``` A table: the entities with one set of component columns ([`World.Describe`](https://ecs.xgamedev.net/en/docs/reference/world#describe)). **Parameters** - `Columns`: The component columns, in bit order (change-tick and [`Disabled`](https://ecs.xgamedev.net/en/docs/reference/disabled) columns not listed). - `Entities`: Living entities. - `Rows`: Rows in use: the entities and the holes a query in progress left (closed when it ends). - `Capacity`: Rows allocated. - `Bytes`: Memory of the rows allocated: columns, change ticks, presence bits and entity slots (not the objects managed components reference). ## Properties ### `Bytes` ```csharp public long Bytes { get; init; } ``` Memory of the rows allocated: columns, change ticks, presence bits and entity slots (not the objects managed components reference). ### `Capacity` ```csharp public int Capacity { get; init; } ``` Rows allocated. ### `Columns` ```csharp public ColumnInfo[] Columns { get; init; } ``` The component columns, in bit order (change-tick and [`Disabled`](https://ecs.xgamedev.net/en/docs/reference/disabled) columns not listed). ### `Entities` ```csharp public int Entities { get; init; } ``` Living entities. ### `Rows` ```csharp public int Rows { get; init; } ``` Rows in use: the entities and the holes a query in progress left (closed when it ends). ## Methods ### `Deconstruct` ```csharp public void Deconstruct(out ColumnInfo[] Columns, out int Entities, out int Rows, out int Capacity, out long Bytes); ``` ### `Equals` ```csharp public bool Equals(TableInfo other); public override bool Equals(object obj); ``` ### `GetHashCode` ```csharp public override int GetHashCode(); ``` ### `ToString` ```csharp public override string ToString(); ``` ## Operators ### `operator !=` ```csharp public static bool operator !=(TableInfo left, TableInfo right); ``` ### `operator ==` ```csharp public static bool operator ==(TableInfo left, TableInfo right); ``` --- # TargetPolicy > What happens to the links to an entity when it is destroyed (TargetRules.WhenTargetDestroyed, RelationIndex.WhenTargetDestroyed). URL: https://ecs.xgamedev.net/en/docs/reference/targetpolicy Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/targetpolicy.md ```csharp public enum TargetPolicy ``` What happens to the links to an entity when it is destroyed ([`TargetRules.WhenTargetDestroyed`](https://ecs.xgamedev.net/en/docs/reference/targetrules#whentargetdestroyed), [`RelationIndex.WhenTargetDestroyed`](https://ecs.xgamedev.net/en/docs/reference/relationindex#whentargetdestroyed)). ## Fields ### `Destroy` ```csharp Destroy = 2; ``` The linking entities are destroyed too, and what links to them in turn (as [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) does). ### `Keep` ```csharp Keep = 0; ``` The links stay, findable by the destroyed id (which no later entity has); a system cleans them. ### `Remove` ```csharp Remove = 1; ``` The links go: the component is removed from its entities, a relation's links are dropped. --- # TargetRules > Target policies of components that point at an entity (IIndexed of EntityId). URL: https://ecs.xgamedev.net/en/docs/reference/targetrules Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/targetrules.md ```csharp public static class TargetRules ``` Target policies of components that point at an entity ([`IIndexed`](https://ecs.xgamedev.net/en/docs/reference/iindexed) of [`EntityId`](https://ecs.xgamedev.net/en/docs/reference/entityid)). ## Methods ### `WhenTargetDestroyed` ```csharp public static ValueIndex WhenTargetDestroyed(this ValueIndex index, TargetPolicy policy) where T : struct, IComponent, IIndexed; ``` Decide what destroying an entity does to the `T` components whose key is that entity: an owner whose pet dies loses its `Pet` ([`TargetPolicy.Remove`](https://ecs.xgamedev.net/en/docs/reference/targetpolicy#remove)), a summon dies with its summoner ([`TargetPolicy.Destroy`](https://ecs.xgamedev.net/en/docs/reference/targetpolicy#destroy)). [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) is [`TargetPolicy.Destroy`](https://ecs.xgamedev.net/en/docs/reference/targetpolicy#destroy) from the start; others are [`TargetPolicy.Keep`](https://ecs.xgamedev.net/en/docs/reference/targetpolicy#keep). Applied inside every destroy (the index is kept built); O(1) per destroyed entity, O(1) per link it had. Owner thread only. --- # UpdateAfterAttribute > Run this system after TSystem (and systems derived from it) of the same group: see UpdateBeforeAttribute. URL: https://ecs.xgamedev.net/en/docs/reference/updateafterattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/updateafterattribute.md ```csharp public sealed class UpdateAfterAttribute : Attribute where TSystem : EcsSystem ``` Run this system after `TSystem` (and systems derived from it) of the same group: see [`UpdateBeforeAttribute`](https://ecs.xgamedev.net/en/docs/reference/updatebeforeattribute). ## Constructors ### `UpdateAfterAttribute` ```csharp public UpdateAfterAttribute(); ``` --- # UpdateBeforeAttribute > Run this system before TSystem (and systems derived from it) of the same group, whatever their registration order. URL: https://ecs.xgamedev.net/en/docs/reference/updatebeforeattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/updatebeforeattribute.md ```csharp public sealed class UpdateBeforeAttribute : Attribute where TSystem : EcsSystem ``` Run this system before `TSystem` (and systems derived from it) of the same group, whatever their registration order. Without an ordering, systems run in registration order; either way, of two systems whose access conflicts the earlier one always finishes first, and systems with no ordering and no conflict between them may run at the same time ([`WorldOptions.ParallelSystems`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#parallelsystems)). The order is resolved once, when a system is added; a cycle throws there, and the analyzer reports cycles it can see (EECS019). ## Constructors ### `UpdateBeforeAttribute` ```csharp public UpdateBeforeAttribute(); ``` --- # UpdateInGroupAttribute > Puts the system (and derived systems) into group TGroup. The UpdateInGroupAttribute class of EasyEcs, the C# ECS. URL: https://ecs.xgamedev.net/en/docs/reference/updateingroupattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/updateingroupattribute.md ```csharp public sealed class UpdateInGroupAttribute : Attribute where TGroup : struct, ISystemGroup ``` Puts the system (and derived systems) into group `TGroup`. ## Constructors ### `UpdateInGroupAttribute` ```csharp public UpdateInGroupAttribute(); ``` --- # ValueIndex > The value index of component T in one world (World.Index). The ValueIndex class of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/valueindex Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference/valueindex.md ```csharp public sealed class ValueIndex where T : struct, IComponent, IIndexed where TKey : IEquatable ``` The value index of component `T` in one world ([`World.Index`](https://ecs.xgamedev.net/en/docs/reference/world#index)). It is kept current as values are written: `Set` and `CreateEntity` re-index the entity at once (O(1)), and entities leave it as soon as they are destroyed or lose the component, so a lookup does no catching up. The first lookup (and the first after [`World.Restore`](https://ecs.xgamedev.net/en/docs/reference/world#restore)) indexes every row once. Lookups allocate nothing once every key has been seen; the index belongs to the world's owner thread, like component values (systems that look up from `OnUpdate` or instance methods run alone). ## Methods ### `Count` ```csharp public int Count(TKey key); ``` Number of entities with key `key`: O(1) (a hash probe, or an array access for a relation to an entity of this world; the first lookup indexes every row once). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Find` ```csharp public ValueIndex.Matches Find(TKey key); ``` The entities whose `T` has key `key` (none for a null key): O(1), then O(1) per entity (the first lookup indexes every row once). Owner thread only. Destroying entities during the loop is allowed; changing `T` is not (an emptied key hands its list to the keys that grow next): collect the entities first, then change them. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1), then O(1) per entity ### `TryFind` ```csharp public bool TryFind(TKey key, out Entity entity); ``` The first entity found with key `key` (any, when several have it). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) --- # ValueIndex.Matches > Enumerates the entities of one key (foreach). The ValueIndex.Matches struct of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/valueindex-matches Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/valueindex-matches.md ```csharp public ref struct Matches ``` Nested in [`ValueIndex`](https://ecs.xgamedev.net/en/docs/reference/valueindex). Enumerates the entities of one key (`foreach`). ## Properties ### `Current` ```csharp public readonly Entity Current { get; } ``` The current matching entity. ## Methods ### `GetEnumerator` ```csharp public readonly ValueIndex.Matches GetEnumerator(); ``` The enumerator itself (`foreach` support, no allocation). ### `MoveNext` ```csharp public bool MoveNext(); ``` Move to the next entity with the key. O(1) per entity. --- # ValueIndex.Ordered > Enumerates entities in key order (foreach): every entity of a key, then the next key. URL: https://ecs.xgamedev.net/en/docs/reference/valueindex-ordered Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/valueindex-ordered.md ```csharp public ref struct Ordered ``` Nested in [`ValueIndex`](https://ecs.xgamedev.net/en/docs/reference/valueindex). Enumerates entities in key order (`foreach`): every entity of a key, then the next key. O(log keys) to start, O(1) per entity and per key. Destroying entities during the loop is allowed, changing `T` is not. ## Properties ### `Current` ```csharp public readonly Entity Current { get; } ``` The current entity. ### `Key` ```csharp public readonly TKey Key { get; } ``` The key of [`ValueIndex.Ordered.Current`](https://ecs.xgamedev.net/en/docs/reference/valueindex-ordered#current). ## Methods ### `GetEnumerator` ```csharp public readonly ValueIndex.Ordered GetEnumerator(); ``` The enumerator itself (`foreach` support, no allocation). ### `MoveNext` ```csharp public bool MoveNext(); ``` Move to the next entity, in key order. --- # WithAnyAttribute > The ForEachAttribute method requires at least one of the components named by its [WithAny] attributes (not passed in)… URL: https://ecs.xgamedev.net/en/docs/reference/withanyattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/withanyattribute.md ```csharp public sealed class WithAnyAttribute : Attribute where T : struct, IComponent ``` The [`ForEachAttribute`](https://ecs.xgamedev.net/en/docs/reference/foreachattribute) method requires at least one of the components named by its `[WithAny]` attributes (not passed in): `[ForEach, WithAny, WithAny]`. On a system group, every [ForEach] method of the group's systems requires one of the group's. ## Constructors ### `WithAnyAttribute` ```csharp public WithAnyAttribute(); ``` --- # WithAttribute > The ForEachAttribute method also requires component T (not passed in). URL: https://ecs.xgamedev.net/en/docs/reference/withattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/withattribute.md ```csharp public sealed class WithAttribute : Attribute where T : struct, IComponent ``` The [`ForEachAttribute`](https://ecs.xgamedev.net/en/docs/reference/foreachattribute) method also requires component `T` (not passed in). On a system group (an [`ISystemGroup`](https://ecs.xgamedev.net/en/docs/reference/isystemgroup) struct), every [ForEach] method of the group's systems does. ## Constructors ### `WithAttribute` ```csharp public WithAttribute(); ``` --- # WithoutAttribute > The ForEachAttribute method skips entities having component T. The WithoutAttribute class of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/withoutattribute Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/withoutattribute.md ```csharp public sealed class WithoutAttribute : Attribute where T : struct, IComponent ``` The [`ForEachAttribute`](https://ecs.xgamedev.net/en/docs/reference/foreachattribute) method skips entities having component `T`. On a system group (an [`ISystemGroup`](https://ecs.xgamedev.net/en/docs/reference/isystemgroup) struct), every [ForEach] method of the group's systems does: ```csharp [Without] public struct Gameplay : ISystemGroup; ``` ## Constructors ### `WithoutAttribute` ```csharp public WithoutAttribute(); ``` --- # World > An ECS world: entities, their components, singletons and the systems that update them. URL: https://ecs.xgamedev.net/en/docs/reference/world Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference/world.md ```csharp public sealed class World : IDisposable ``` An ECS world: entities, their components, singletons and the systems that update them. Worlds are fully isolated; the recommended server layout is one world per thread, which needs no synchronization at all. ## Constructors ### `World` ```csharp public World(WorldOptions options = null); ``` A new, empty world configured by `options` (null: the defaults). O([`WorldOptions.InitialEntityCapacity`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#initialentitycapacity)): allocates the entity array and the empty table. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(`InitialEntityCapacity`) ## Fields ### `ParallelChunkRows` ```csharp public const int ParallelChunkRows = 16384; ``` The most rows per chunk of a parallel [ForEach]. Chunks hold about a quarter of each thread's share of the matching rows (at least 1,024): equal chunks finish together, and four per thread even out uneven rows. ## Properties ### `ChangeTick` ```csharp public ulong ChangeTick { get; } ``` The current change tick, stamped into tracked components' rows on every write ([`ITrackChanges`](https://ecs.xgamedev.net/en/docs/reference/itrackchanges)). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Entities` ```csharp public World.EntityEnumerator Entities { get; } ``` All alive entities in id order (diagnostics: O(capacity)). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(capacity) ### `EntityCount` ```csharp public int EntityCount { get; } ``` Number of alive entities. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Systems` ```csharp public SystemList Systems { get; } ``` Systems of every group, each group in execution order (default group first). Allocation-free. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(systems) to walk, `Count` O(groups) ### `UpdateCount` ```csharp public long UpdateCount { get; } ``` Number of completed [`World.Update`](https://ecs.xgamedev.net/en/docs/reference/world#update) calls (default group). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ## Methods ### `AddSingleton` ```csharp public ref T AddSingleton() where T : struct, ISingletonComponent; ``` Add (or reset to default) singleton `T` and return a ref to it. A reset keeps the storage, so [`World.SingletonRef`](https://ecs.xgamedev.net/en/docs/reference/world#singletonref) handles taken before still reach the singleton. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `AddSystem` ```csharp public void AddSystem(EcsSystem system, bool changesFromNow = false); ``` Attach `system` to its group ([`UpdateInGroupAttribute`](https://ecs.xgamedev.net/en/docs/reference/updateingroupattribute), default otherwise) and call its [`EcsSystem.OnCreate`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#oncreate). **Parameters** - `system`: The system, not attached to a world yet. - `changesFromNow`: False (the default): the first run of its `[Changed]` and `[Removed]` methods visits every row written or removed since the world began. True: only what is written or removed after this call, as if the system had run just now ([`EcsSystem.LastRunTick`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#lastruntick)); for a system added to a world that already holds its state (a restart after [`World.Load`](https://ecs.xgamedev.net/en/docs/reference/world#load), a system switched on later). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.AddSystem(changesFromNow)`: O(s²), s = systems of its group - `AddSystem(system, changesFromNow)`: O(s²), s = systems of its group ### `AddSystem` ```csharp public T AddSystem(bool changesFromNow = false) where T : EcsSystem, new(); ``` Create a system, attach it to this world and call its [`EcsSystem.OnCreate`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#oncreate). **Parameters** - `changesFromNow`: See [`World.AddSystem`](https://ecs.xgamedev.net/en/docs/reference/world#addsystem). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.AddSystem(changesFromNow)`: O(s²), s = systems of its group - `AddSystem(system, changesFromNow)`: O(s²), s = systems of its group ### `Any` ```csharp public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent; public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent; public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public bool Any(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Whether any alive entity has all of `T1, T2`. O(matching archetypes), plus O(rows / 64) for tables with rows to test; early exit. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S / 64) worst ### `Capture` ```csharp public WorldSnapshot Capture(); ``` Copy the entities, their components and the singletons. O(entities × components + archetypes + singletons). Components and singletons are copied by value: a managed reference inside one is shared, not cloned. Not while a pass iterates. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.Capture()`: O(entities × components + tables + singletons) - `Capture(into)`: O(entities × components + tables + singletons) ### `Capture` ```csharp public WorldSnapshot Capture(WorldSnapshot into); ``` [`World.Capture`](https://ecs.xgamedev.net/en/docs/reference/world#capture) into `into` (a snapshot of this world, or null for a new one), overwriting it and reusing its arrays: capturing every tick (rollback, replays) allocates nothing once they are large enough. Returns the snapshot. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.Capture()`: O(entities × components + tables + singletons) - `Capture(into)`: O(entities × components + tables + singletons) ### `Children` ```csharp public ValueIndex.Matches Children(EntityId parent); ``` The children of `parent`: the entities whose [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) points at it. O(1), then O(1) per child; the first call indexes every [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) once. Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1), then O(1) per child ### `Count` ```csharp public int Count(in QueryFilter filter = default) where T1 : struct, IComponent; public int Count(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent; public int Count(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public int Count(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public int Count(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public int Count(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public int Count(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public int Count(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public int Count(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Number of alive entities having all of `T1, T2`. O(matching archetypes), plus O(rows / 64) for tables with rows to test. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M), + S / 64 for tables whose rows must be tested ### `CreateEntities` ```csharp public void CreateEntities(Span entities, in T1 c1) where T1 : struct, IComponent; public void CreateEntities(Span entities, in T1 c1, in T2 c2) where T1 : struct, IComponent where T2 : struct, IComponent; public void CreateEntities(Span entities, in T1 c1, in T2 c2, in T3 c3) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public void CreateEntities(Span entities, in T1 c1, in T2 c2, in T3 c3, in T4 c4) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public void CreateEntities(Span entities, in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public void CreateEntities(Span entities, in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public void CreateEntities(Span entities, in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public void CreateEntities(Span entities, in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7, in T8 c8) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public void CreateEntities(Span entities, in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7, in T8 c8, in T9 c9) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Create `entities.Length` entities with 2 components (the same values for each), placed directly in their final archetype, and write their handles to `entities`. One pass through the structural gate and at most one table growth: O(count × 2). Owner thread only (see docs/content/guide/threading.md). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(count × n) amortized ### `CreateEntity` ```csharp public Entity CreateEntity(); ``` Create an entity without components. O(1) amortized. Owner thread only (see docs/content/guide/threading.md). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.CreateEntity()`: O(1) amortized - `world.CreateEntity(in T1 … in Tn)`: O(n) amortized ### `CreateEntity` ```csharp public Entity CreateEntity(in T1 c1) where T1 : struct, IComponent; public Entity CreateEntity(in T1 c1, in T2 c2) where T1 : struct, IComponent where T2 : struct, IComponent; public Entity CreateEntity(in T1 c1, in T2 c2, in T3 c3) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public Entity CreateEntity(in T1 c1, in T2 c2, in T3 c3, in T4 c4) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public Entity CreateEntity(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public Entity CreateEntity(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public Entity CreateEntity(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public Entity CreateEntity(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7, in T8 c8) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public Entity CreateEntity(in T1 c1, in T2 c2, in T3 c3, in T4 c4, in T5 c5, in T6 c6, in T7 c7, in T8 c8, in T9 c9) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Create an entity with 2 components placed directly in its final archetype (no intermediate moves). O(2) amortized. Owner thread only (see docs/content/guide/threading.md). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.CreateEntity()`: O(1) amortized - `world.CreateEntity(in T1 … in Tn)`: O(n) amortized ### `Descendants` ```csharp public World.Subtree Descendants(EntityId root); ``` The descendants of `root`, depth first, each before its own children: its children, their children, and so on (`root` itself is not one). What a save of a subtree collects: `ids.Add(root.Id); foreach (var e in world.Descendants(root.Id)) ids.Add(e.Id);`. O(1) per entity; the first walk indexes every [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) once. Allocates nothing once warm (the walk's stack is kept by the world). An entity destroyed during the walk is skipped. Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) per entity of the subtree ### `Describe` ```csharp public TableInfo[] Describe(); ``` The world's tables, for diagnostics (an admin endpoint, a dashboard): what each holds, how full it is and what it costs. Cold: allocates the result; any thread (a table being changed at the same time may be read half-way). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(tables + columns) ### `DestroyEntities` ```csharp public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent; public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent; public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public int DestroyEntities(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Destroy every alive entity having all of `T1, T2` (and matching `filter`) and return how many. One pass through the structural gate: O(matching archetypes + rows). Owner thread only (see docs/content/guide/threading.md). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S) ### `DisableAll` ```csharp public int DisableAll(in QueryFilter filter = default) where T : struct, IComponent; ``` [`Entity.Disable`](https://ecs.xgamedev.net/en/docs/reference/entity#disable) on every alive entity having `T` and matching `filter`: each keeps its value and gets [`Disabled`](https://ecs.xgamedev.net/en/docs/reference/disabled). Returns how many. O(matching tables + rows); a table's rows move once, to the table with the tag. Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S) ### `Dispose` ```csharp public void Dispose(); ``` Destroy all systems (OnDestroy in reverse order), then release all storage. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(systems + entities + tables) ### `EnableAll` ```csharp public int EnableAll(in QueryFilter filter = default) where T : struct, IComponent; ``` [`Entity.Enable`](https://ecs.xgamedev.net/en/docs/reference/entity#enable) on every alive entity with `T` disabled and matching `filter`: each gets its kept value back (a write of a tracked component; indexes follow). Returns how many. O(matching tables + rows). Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S) ### `EnsureCapacity` ```csharp public void EnsureCapacity(Prefab prefab, int count); ``` Pre-size the table `prefab`'s instances go to, and the entity storage, so the next `count` [`World.Instantiate`](https://ecs.xgamedev.net/en/docs/reference/world#instantiate) calls never grow them: a wave of spawns pays its growth before the tick. Instances whose groups put them in another table ([`World.GroupBy`](https://ecs.xgamedev.net/en/docs/reference/world#groupby)) grow that one. For a prefab with members, every member's table. O(components) plus one growth. Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.EnsureCapacity(count)`: O(n), plus one growth - `world.EnsureCapacity(prefab, count)`: O(c), plus one growth ### `EnsureCapacity` ```csharp public void EnsureCapacity(int count) where T1 : struct, IComponent; public void EnsureCapacity(int count) where T1 : struct, IComponent where T2 : struct, IComponent; public void EnsureCapacity(int count) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public void EnsureCapacity(int count) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public void EnsureCapacity(int count) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public void EnsureCapacity(int count) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public void EnsureCapacity(int count) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public void EnsureCapacity(int count) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public void EnsureCapacity(int count) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Pre-size the table of entities with exactly `T1, T2` and the entity storage, so the next `count` `CreateEntity` / `CreateEntities` calls with these components never grow them: a start-up or a wave of spawns pays its growth once, before the loop. Entities whose groups put them in another table ([`World.GroupBy`](https://ecs.xgamedev.net/en/docs/reference/world#groupby)) grow that one; components added later move entities to other tables, which grow on their own. O(2) plus one growth. Owner thread only (see docs/content/guide/threading.md). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.EnsureCapacity(count)`: O(n), plus one growth - `world.EnsureCapacity(prefab, count)`: O(c), plus one growth ### `EnsureEntityCapacity` ```csharp public void EnsureEntityCapacity(int capacity); ``` Pre-size entity storage so creating up to `capacity` entities never grows it. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(capacity) ### `ForEach` ```csharp public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where TJob : struct, IForEach, allows ref struct; public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where TJob : struct, IForEach, allows ref struct; public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where TJob : struct, IForEach, allows ref struct; public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where TJob : struct, IForEach, allows ref struct; public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where TJob : struct, IForEach, allows ref struct; public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where TJob : struct, IForEach, allows ref struct; public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where TJob : struct, IForEach, allows ref struct; public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where TJob : struct, IForEach, allows ref struct; public void ForEach(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent where TJob : struct, IForEach, allows ref struct; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Run `job` with the components for every entity having all of `T1, T2` (and matching `filter`). The fastest iteration: walks each matching archetype's columns front to back, O(matching archetypes + rows), allocation-free. Structural changes inside the job are allowed and take effect immediately: an entity is visited at most once (entities that enter a matching archetype during the pass are not visited, entities that leave before their turn are skipped), and when the job changes the archetype of the entity it visits, its writes through the refs are carried over to the entity's new row (`IForEach.Writes`). A job implementing [`INoStructuralChanges`](https://ecs.xgamedev.net/en/docs/reference/inostructuralchanges) skips that bookkeeping. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S) ### `ForEachBatch` ```csharp public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; public void ForEachBatch(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent where TJob : struct, IForEachBatch, allows ref struct; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Run `job` over every entity having all of `T1, T2` (and matching `filter`), one run of consecutive rows at a time: a dense archetype is a single call. Allocation-free. The job sees spans into the tables, so structural changes throw while it runs (`InvalidOperationException`). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S / 64 + runs) ### `ForEachEntity` ```csharp public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; public void ForEachEntity(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent where TJob : struct, IForEachEntity, allows ref struct; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Run `job` with the entity handle for every entity having all of `T1, T2` (and matching `filter`). The fastest iteration: walks each matching archetype's columns front to back, O(matching archetypes + rows), allocation-free. Structural changes inside the job are allowed and take effect immediately: an entity is visited at most once (entities that enter a matching archetype during the pass are not visited, entities that leave before their turn are skipped), and when the job changes the archetype of the entity it visits, its writes through the refs are carried over to the entity's new row (`IForEachEntity.Writes`). A job implementing [`INoStructuralChanges`](https://ecs.xgamedev.net/en/docs/reference/inostructuralchanges) skips that bookkeeping. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S) ### `ForEachEntityParallel` ```csharp public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; public void ForEachEntityParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent where TJob : struct, IForEachEntity, INoStructuralChanges; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. [`World.ForEachEntity`](https://ecs.xgamedev.net/en/docs/reference/world#foreachentity) on several threads: the matching rows are cut into chunks (about four per thread, a multiple of 64 rows, at most [`World.ParallelChunkRows`](https://ecs.xgamedev.net/en/docs/reference/world#parallelchunkrows)) that the calling thread and up to [`WorldOptions.MaxDegreeOfParallelism`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#maxdegreeofparallelism) - 1 thread-pool threads run at the same time, each with its own copy of `job` (state a job keeps in its fields is not merged back). The job must not change structure or write anything that another row's run reads (a singleton, another entity); nothing else may change the world during the call. Fewer than two chunks of rows, or a runner already busy, run on the calling thread. Allocation-free after the first call per job type. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S), divided over up to `MaxDegreeOfParallelism` threads ### `ForEachParallel` ```csharp public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; public void ForEachParallel(ref TJob job, in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent where TJob : struct, IForEach, INoStructuralChanges; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. [`World.ForEach`](https://ecs.xgamedev.net/en/docs/reference/world#foreach) on several threads: the matching rows are cut into chunks (about four per thread, a multiple of 64 rows, at most [`World.ParallelChunkRows`](https://ecs.xgamedev.net/en/docs/reference/world#parallelchunkrows)) that the calling thread and up to [`WorldOptions.MaxDegreeOfParallelism`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#maxdegreeofparallelism) - 1 thread-pool threads run at the same time, each with its own copy of `job` (state a job keeps in its fields is not merged back). The job must not change structure or write anything that another row's run reads (a singleton, another entity); nothing else may change the world during the call. Fewer than two chunks of rows, or a runner already busy, run on the calling thread. Allocation-free after the first call per job type. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S), divided over up to `MaxDegreeOfParallelism` threads ### `GetEntity` ```csharp public Entity GetEntity(EntityId id); ``` The handle of entity `id`; throws if that incarnation is not alive. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `GetOrAddSingleton` ```csharp public ref T GetOrAddSingleton() where T : struct, ISingletonComponent; ``` Ref to singleton `T`, adding it (default) first if missing. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `GetSingleton` ```csharp public ref T GetSingleton() where T : struct, ISingletonComponent; ``` Ref to singleton `T`; throws if it was not added. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `GetSystem` ```csharp public T GetSystem() where T : EcsSystem; ``` Get the system of type `T`, or null. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(systems) ### `GroupBy` ```csharp public void GroupBy() where T : struct, IComponent, IGroup; ``` Split this world's tables by `T`'s [`IGroup.Group`](https://ecs.xgamedev.net/en/docs/reference/igroup#group): entities of one group share tables, so [`QueryFilter.InGroup`](https://ecs.xgamedev.net/en/docs/reference/queryfilter#ingroup) walks only that group's rows, contiguous in memory. Setting a new value moves the entity to its group's tables (one row copy). Existing entities move now: call it at setup. O(entities with `T`) once; idempotent. Owner thread only, not during a pass. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(entities with `T`), once ### `HasSingleton` ```csharp public bool HasSingleton() where T : struct, ISingletonComponent; ``` Whether singleton `T` exists. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Index` ```csharp public ValueIndex Index() where T : struct, IComponent, IIndexed where TKey : IEquatable; ``` The value index of `T`: find entities by `T`'s key, or by the entity a relation component points at. Created on the first call (cold), O(1) after; keep it in a local or field. Throws `InvalidOperationException` when `T` is already indexed by another key type. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1); the first call creates it ### `Instantiate` ```csharp public Entity Instantiate(Prefab prefab); ``` Create an entity with a copy of every component of `prefab`. Values are copied as they are: a [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer) gets a list of its own, indexes learn the new entity, tracked components count as written now. O(components): one row copy, no table search after the first instance. A prefab with members creates them all and returns the entity of the one passed (O(members × components)). Owner thread only (see docs/content/guide/threading.md). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.Instantiate(prefab)`: O(c) - `world.Instantiate(prefab, Span entities)`: O(count × c) ### `Instantiate` ```csharp public void Instantiate(Prefab prefab, Span entities); ``` [`World.Instantiate`](https://ecs.xgamedev.net/en/docs/reference/world#instantiate) for `entities.Length` copies of `prefab`, whose handles are written to `entities`: one pass through the structural gate and at most one table growth. O(count × components). Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.Instantiate(prefab)`: O(c) - `world.Instantiate(prefab, Span entities)`: O(count × c) ### `IsAlive` ```csharp public bool IsAlive(EntityId id); ``` Whether entity `id` (that incarnation) is alive. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Load` ```csharp public void Load(ReadOnlySpan input, bool markWritten = true); ``` Replace this world's entities, components and singletons with those [`World.Save`](https://ecs.xgamedev.net/en/docs/reference/world#save) wrote (in this process or another). Entities keep their ids and versions, so [`EntityId`](https://ecs.xgamedev.net/en/docs/reference/entityid)s stored in components still point at the same entities, and handles made before the save work again. Components and singletons this process has no type for are skipped (their slices); a type is found by its type id when the process used it or the generator registered it (every component and singleton of a compilation using EasyEcs). Indexes rebuild; groups follow this world's [`World.GroupBy`](https://ecs.xgamedev.net/en/docs/reference/world#groupby). O(entities × components). Not while a pass iterates. **Parameters** - `input`: The bytes of the save. - `markWritten`: True (the default): every loaded row counts as written now, so `[Changed]` systems and `Changed(since)` queries see it. False: the loaded components have no change tick, as if never written, and no row counts as removed; a system added after the load skips them on its first run too (its `[Changed]` looks at ticks from 1). For a restart that resumes a world saved by another process, whose records already hold the loaded values. **Exceptions** - `InvalidDataException`: The bytes are not a save or are damaged, or a component's fields changed since the save (an unmanaged one's size or layout, a managed one's Nino layout). The world is then left as it was. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(entities × components) ### `LoadEntities` ```csharp public int LoadEntities(ReadOnlySpan input, Span entities = default); ``` Create the entities `SaveEntities` wrote (in this process or another), with new ids, and write their handles in save order into `entities` (as many as fit); returns how many were created. [`EntityId`](https://ecs.xgamedev.net/en/docs/reference/entityid) fields of their components and buffer elements that named an entity of the group name its new entity, every other one is [`EntityId.Null`](https://ecs.xgamedev.net/en/docs/reference/entityid#null) (the generator tells the world where those fields are; ids inside collections are not rewritten). A [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) whose parent stayed behind is removed: the entity is a root here. Indexes and groups learn the entities; tracked components count as written. O(entities × components). Not while a pass iterates. **Exceptions** - `InvalidDataException`: The bytes are not a save. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(entities × components) ### `LoadEntitiesInto` ```csharp public int LoadEntitiesInto(ReadOnlySpan input, ReadOnlySpan into, bool markWritten = true); ``` Put the components [`World.SaveEntities`](https://ecs.xgamedev.net/en/docs/reference/world#saveentities) wrote onto entities that exist already (an actor whose entity was made before its record arrived): the components of the i-th saved entity are set on `into`[i], added or replacing the values it has, each entity moving table at most once; components the save does not hold stay as they are. Indexes, groups and change ticks follow as with `Set` (every loaded component counts as written); a disabled component arrives disabled with its value. [`EntityId`](https://ecs.xgamedev.net/en/docs/reference/entityid) fields that named an entity of the group name the entity of `into` it became, every other one is [`EntityId.Null`](https://ecs.xgamedev.net/en/docs/reference/entityid#null), and a [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) whose parent stayed behind is not set. Returns how many entities were loaded. O(entities × components). Not while a pass iterates. With `markWritten` false, the loaded components do not count as written: each one the save holds has no change tick afterwards, also when it replaces a value written before (a default from a prefab), so `[Changed]` systems and `Since` filters do not visit the entity for the load (an actor restored from storage holds what storage has, and "save what changed" saves nothing of it until code writes it). Components the save does not hold keep their ticks. **Exceptions** - `ArgumentException`: `into` does not hold one living entity of this world per saved entity. - `InvalidDataException`: The bytes are not a save. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(entities × components) ### `MoveEntities` ```csharp public int MoveEntities(World target, ReadOnlySpan entities, Span moved = default); ``` Move `entities` (stale ids and repeats are skipped) into `target`, another world of this thread: the target gets new entities with their components, as [`World.LoadEntities`](https://ecs.xgamedev.net/en/docs/reference/world#loadentities) makes them from a save of the group, without encoding it; then they are destroyed here (their children with them, so move a hierarchy together; cleanup components stay behind for their systems). The new handles are written in order into `moved` (as many as fit, [`Entity`](https://ecs.xgamedev.net/en/docs/reference/entity) default for a skipped id); returns how many moved. O(entities × components). Owner thread of both worlds; not while a pass iterates in either. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(entities × components) ### `Query` ```csharp public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent; public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent; public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent; public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent; public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent; public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent; public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent; public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent; public QueryEnumerator Query(in QueryFilter filter = default) where T1 : struct, IComponent where T2 : struct, IComponent where T3 : struct, IComponent where T4 : struct, IComponent where T5 : struct, IComponent where T6 : struct, IComponent where T7 : struct, IComponent where T8 : struct, IComponent where T9 : struct, IComponent; ``` One overload per number of components, 1 to 9 (generated from one template); this is the text of the two-component one. Enumerate entities having all of `T1, T2` (and matching `filter`). Allocation-free. ### `Relations` ```csharp public RelationIndex Relations() where T : struct, IRelation; ``` The relation index of `T`: the entities whose [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/reference/dynamicbuffer) links to a target. Created on the first call (cold), O(1) after; keep it in a local or field. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1); the first call creates it ### `RemoveAll` ```csharp public int RemoveAll(in QueryFilter filter = default) where T : struct, IComponent; ``` Remove component `T` from every alive entity having it and matching `filter`, as `Remove` would one by one (rows stay, presence bits clear). Returns how many. O(matching tables + rows). Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S) ### `RemoveSingleton` ```csharp public bool RemoveSingleton() where T : struct, ISingletonComponent; ``` Remove singleton `T`; false if it was not added. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `RemoveSystem` ```csharp public bool RemoveSystem() where T : EcsSystem; ``` Remove the system of type `T` (calls its [`EcsSystem.OnDestroy`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#ondestroy)). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(s²) ### `RemoveTypes` ```csharp public void RemoveTypes(Assembly assembly); ``` Remove from this world everything of the types of `assembly`: its systems (OnDestroy runs), singletons, indexes and groupings, and its components from every entity (the entities stay, without them). Tables that had such a column are dropped, with every cache that names them, so the world holds no reference to the assembly any more: once every world removed it, its collectible context can unload, and when it does, EasyEcs reuses its component bits. To reload game logic and keep its data: [`World.Save`](https://ecs.xgamedev.net/en/docs/reference/world#save), remove the types, unload the old context, load the new version, then [`World.Load`](https://ecs.xgamedev.net/en/docs/reference/world#load) (types are saved by type id, so the new version's components take the values). Owner thread only, not during a pass or an update. O(entities with such components + tables + cached queries); allocates (cold). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.RemoveTypes(assembly)`: O(entities with such components + tables + cached queries) - `RemoveTypes(context)`: O(entities with such components + tables + cached queries) ### `RemoveTypes` ```csharp public void RemoveTypes(AssemblyLoadContext context); ``` [`World.RemoveTypes`](https://ecs.xgamedev.net/en/docs/reference/world#removetypes) for every assembly loaded into `context` (a plugin and the libraries it brought). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.RemoveTypes(assembly)`: O(entities with such components + tables + cached queries) - `RemoveTypes(context)`: O(entities with such components + tables + cached queries) ### `Restore` ```csharp public void Restore(WorldSnapshot snapshot); ``` Put the world back to `snapshot` (taken from this world). Handles of entities alive in the snapshot are valid again; every other handle is stale, also handles of entities created after the capture. Archetypes created after the capture stay, empty. Singletons keep their boxes (a [`World.SingletonRef`](https://ecs.xgamedev.net/en/docs/reference/world#singletonref) still works) and get the snapshot's values; singletons added after the capture are removed. O(entities × components + archetypes + singletons). Not while a pass iterates. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(entities × components + tables + singletons) ### `Save` ```csharp public void Save(IBufferWriter output); ``` Write the entities (ids and versions), their components and the singletons into `output`, for [`World.Load`](https://ecs.xgamedev.net/en/docs/reference/world#load). Unmanaged components are their raw rows (a layout change makes old saves unloadable) unless they are `[NinoType]`s, whose formatter writes them (its format decides what a type may change: fields appended with `VersionTolerant`, any change of members with `Keyed`); managed components and singletons need a Nino formatter. Types are recorded by Nino type id: a type renamed with `[NinoFormerName]` loads its old rows. Allocates nothing once its buffers are large enough. O(entities × components). Not while a pass iterates. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(entities × components) ### `SaveEntities` ```csharp public void SaveEntities(IBufferWriter output, ReadOnlySpan entities); ``` Write `entities` (stale ids and repeats are skipped) and their components into `output`, for [`World.LoadEntities`](https://ecs.xgamedev.net/en/docs/reference/world#loadentities) or [`World.LoadEntitiesInto`](https://ecs.xgamedev.net/en/docs/reference/world#loadentitiesinto): a group of entities that moves to another world (a player and what it owns, to another server). Singletons and the other entities are not written; collect a hierarchy with [`World.Descendants`](https://ecs.xgamedev.net/en/docs/reference/world#descendants). Allocates nothing once its buffers are large enough. O(entities given × components). Not while a pass iterates. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.SaveEntities(output, ids)`: O(entities given × components) - `world.SaveEntities(output, ids, set)`: O(entities given × components) ### `SaveEntities` ```csharp public void SaveEntities(IBufferWriter output, ReadOnlySpan entities, in ComponentSet components); ``` [`World.SaveEntities`](https://ecs.xgamedev.net/en/docs/reference/world#saveentities) of the components in `components` only (a record of the components that persist, without the runtime ones): the others are not written and need no Nino formatter; a tag is written as present or not, a disabled component with its kept value. Entities without any of them are written too, empty. Allocates nothing once its buffers are large enough. O(entities given × components). Not while a pass iterates. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.SaveEntities(output, ids)`: O(entities given × components) - `world.SaveEntities(output, ids, set)`: O(entities given × components) ### `SetAll` ```csharp public int SetAll(in T value, in QueryFilter filter = default) where T : struct, IComponent; ``` Give every alive entity matching `filter` component `T` = `value` (added, or replaced), as `Set` would one by one: tracked components count as written, indexes and groups follow. Returns how many entities. O(matching tables + rows); an entity that lacks `T` moves once. Owner thread only. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(M + S) ### `SingletonRef` ```csharp public SingletonRef SingletonRef() where T : struct, ISingletonComponent; ``` Stable handle to singleton `T`; throws if it was not added: resolve it once, then read and write [`SingletonRef.Value`](https://ecs.xgamedev.net/en/docs/reference/singletonref#value) without a lookup. Generated `[ForEach]` jobs resolve singleton parameters through it once per pass, so a system whose singleton was never set fails on its first run. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `TryGetEntity` ```csharp public bool TryGetEntity(EntityId id, out Entity entity); ``` The handle of entity `id` if that incarnation is alive; false for a destroyed entity (even when its index was reused) and for [`EntityId.Null`](https://ecs.xgamedev.net/en/docs/reference/entityid#null). O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `TryGetSingleton` ```csharp public bool TryGetSingleton(out T value) where T : struct, ISingletonComponent; ``` Copy of singleton `T` if present. O(1). **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): O(1) ### `Update` ```csharp public void Update(); ``` Run one update of every enabled system of the default group (synchronous). Allocation-free. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.Update()`: Σ systems of the group - `world.Update()`: Σ systems of the group ### `Update` ```csharp public void Update() where TGroup : struct, ISystemGroup; ``` Run one update of every enabled system in group `TGroup` (synchronous, allocation-free). A group with no systems is a no-op. **Complexity** ([API table](https://ecs.xgamedev.net/en/docs/api)): - `world.Update()`: Σ systems of the group - `world.Update()`: Σ systems of the group --- # World.DescendantWalk > A depth-first walk of World.Descendants: a stack of the child lists still being read, given back to the world by World.DescendantWalk.Dispose… URL: https://ecs.xgamedev.net/en/docs/reference/world-descendantwalk Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference/world-descendantwalk.md ```csharp public ref struct DescendantWalk ``` Nested in [`World`](https://ecs.xgamedev.net/en/docs/reference/world). A depth-first walk of [`World.Descendants`](https://ecs.xgamedev.net/en/docs/reference/world#descendants): a stack of the child lists still being read, given back to the world by [`World.DescendantWalk.Dispose`](https://ecs.xgamedev.net/en/docs/reference/world-descendantwalk#dispose) (`foreach` calls it). ## Properties ### `Current` ```csharp public readonly Entity Current { get; } ``` The current descendant. ## Methods ### `Dispose` ```csharp public void Dispose(); ``` Give the stack back to the world for the next walk. ### `MoveNext` ```csharp public bool MoveNext(); ``` Move to the next descendant. O(1) per entity, plus one step per list it finishes. **Exceptions** - `InvalidOperationException`: The [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) links form a cycle. --- # World.EntityEnumerator > Enumerates alive entities in id order; ids beyond the capacity captured at start are not visited. URL: https://ecs.xgamedev.net/en/docs/reference/world-entityenumerator Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/world-entityenumerator.md ```csharp public struct EntityEnumerator ``` Nested in [`World`](https://ecs.xgamedev.net/en/docs/reference/world). Enumerates alive entities in id order; ids beyond the capacity captured at start are not visited. ## Properties ### `Current` ```csharp public readonly Entity Current { get; } ``` The current living entity. ## Methods ### `GetEnumerator` ```csharp public readonly World.EntityEnumerator GetEnumerator(); ``` The enumerator itself (`foreach` support, no allocation). ### `MoveNext` ```csharp public bool MoveNext(); ``` Move to the next living entity (ids in ascending order). O(1) amortized per id. --- # World.Subtree > The descendants of an entity (World.Descendants): each foreach walks them anew. URL: https://ecs.xgamedev.net/en/docs/reference/world-subtree Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/reference/world-subtree.md ```csharp public readonly ref struct Subtree ``` Nested in [`World`](https://ecs.xgamedev.net/en/docs/reference/world). The descendants of an entity ([`World.Descendants`](https://ecs.xgamedev.net/en/docs/reference/world#descendants)): each `foreach` walks them anew. ## Methods ### `GetEnumerator` ```csharp public World.DescendantWalk GetEnumerator(); ``` A walk over the descendants (`foreach` support, no allocation once warm). **Exceptions** - `InvalidOperationException`: The [`ChildOf`](https://ecs.xgamedev.net/en/docs/reference/childof) links form a cycle (when the walk reaches it). --- # WorldOptions > Configuration of a World. The WorldOptions class of EasyEcs, the C# ECS: its members, parameters and complexity. URL: https://ecs.xgamedev.net/en/docs/reference/worldoptions Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/worldoptions.md ```csharp public sealed class WorldOptions ``` Configuration of a [`World`](https://ecs.xgamedev.net/en/docs/reference/world). ## Constructors ### `WorldOptions` ```csharp public WorldOptions(); ``` ## Properties ### `InitialEntityCapacity` ```csharp public int InitialEntityCapacity { get; init; } ``` Pre-sized entity capacity (avoid growth reallocations at runtime). ### `MaxDegreeOfParallelism` ```csharp public int MaxDegreeOfParallelism { get; init; } ``` Threads one parallel run uses at most (default: processor count): systems run by [`WorldOptions.ParallelSystems`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#parallelsystems), and the row chunks of parallel `[ForEach]` methods, `ForEachParallel` and `ForEachEntityParallel` (which run in chunks whether [`WorldOptions.ParallelSystems`](https://ecs.xgamedev.net/en/docs/reference/worldoptions#parallelsystems) is on or not). ### `MeasureSystems` ```csharp public bool MeasureSystems { get; init; } ``` Time every system run into [`EcsSystem.Stats`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#stats) (two timestamp reads per run). Default false. ### `ParallelSystems` ```csharp public bool ParallelSystems { get; init; } ``` Run systems with no order between them at the same time (thread pool) when their generated access does not conflict ([`SystemAccess`](https://ecs.xgamedev.net/en/docs/reference/systemaccess)). Default false: one owner thread per world is the recommended model. ### `SystemErrors` ```csharp public SystemErrorPolicy SystemErrors { get; init; } ``` What an exception thrown by a system does (default [`SystemErrorPolicy.Throw`](https://ecs.xgamedev.net/en/docs/reference/systemerrorpolicy#throw)): propagate out of [`World.Update`](https://ecs.xgamedev.net/en/docs/reference/world#update), or switch the system off and record it in [`EcsSystem.Error`](https://ecs.xgamedev.net/en/docs/reference/ecssystem#error). --- # WorldSnapshot > A copy of a world's entities, components and singletons, taken by World.Capture and put back by World.Restore (systems and options are not part of it). URL: https://ecs.xgamedev.net/en/docs/reference/worldsnapshot Version: EasyEcs 4.6 Last updated: 2026-10-18 中文版: https://ecs.xgamedev.net/zh/docs/reference/worldsnapshot.md ```csharp public sealed class WorldSnapshot ``` A copy of a world's entities, components and singletons, taken by [`World.Capture`](https://ecs.xgamedev.net/en/docs/reference/world#capture) and put back by [`World.Restore`](https://ecs.xgamedev.net/en/docs/reference/world#restore) (systems and options are not part of it). Holds the copies only; it can be restored any number of times, into the world it was taken from. [`World.Capture`](https://ecs.xgamedev.net/en/docs/reference/world#capture-2) overwrites it, reusing its arrays (no allocation once they are large enough). ## Properties ### `EntityCount` ```csharp public int EntityCount { get; } ``` Alive entities in the snapshot. --- # Glossary > Every Entity Component System term the EasyEcs docs use, from entity and archetype to change tick, structural gate and collectible AssemblyLoadContext. URL: https://ecs.xgamedev.net/en/docs/glossary Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/glossary.md The terms of the EasyEcs docs, each in a few sentences with a link to the page that explains it. General ECS terms come first, then the ones specific to EasyEcs. For the pattern itself, start with [What is an ECS?](https://ecs.xgamedev.net/en/docs/what-is-ecs). ## Entity An identity and nothing else: no fields, no methods. In EasyEcs an `Entity` is a 16-byte handle (world, index, version); every access checks the version, so a handle to a destroyed entity throws instead of reaching whatever reuses its index. See [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components). ## EntityId The 8-byte, unmanaged form of an entity: index plus version, without the world. Components store `EntityId`s to point at other entities; `world.TryGetEntity(id, out entity)` turns one back into a checked handle. See [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations). ## Component A struct implementing `IComponent`: plain data for one aspect of an entity (`Position`, `Health`). Components hold no behaviour and no references to systems or services. See [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles). ## Tag A component with no fields (`Dead`, `Stunned`). It only says yes or no, so systems use it in filters (`[Without]`), and adding or removing it never copies data after the first time. See [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components). ## Singleton A struct implementing `ISingletonComponent`: one value per world, such as a clock, configuration or a spatial grid. A `[ForEach]` method takes it as a `ref` or `in` parameter. See [Singletons](https://ecs.xgamedev.net/en/docs/guide/singletons). ## Archetype One combination of component types, and the table that holds every entity with that combination. EasyEcs is an archetype ECS: a query walks the tables whose combination it matches, column by column. See [What is an ECS?](https://ecs.xgamedev.net/en/docs/what-is-ecs#archetypes). ## Table, column, row An archetype's storage. A table has one column per component type (an array, 64-byte aligned for unmanaged types) and one row per entity. Iteration reads the columns a system touches, front to back. See [Architecture](https://ecs.xgamedev.net/en/docs/architecture). ## Presence bit One bit per row and column that says whether the row has that component. Removing a component clears the bit and keeps the row, so toggling a state such as `Stunned` costs a bit flip, not a row move. Filters test the bits 64 rows at a time. See [Architecture](https://ecs.xgamedev.net/en/docs/architecture). ## Query The question "which entities have these components and pass this filter?". A `[ForEach]` method is a query; outside systems, `world.Query()`, `Count`, `Any` and struct jobs ask it. See [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries). ## Filter The conditions of a query beyond its components: `With`, `Without`, `WithAny`, `Changed`, `Removed` and `InGroup`. They are attributes on `[ForEach]` methods, or a `QueryFilter` kept in a `static readonly` field. See [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries#filters). ## Query cache The world's memory of which tables match each query. The first use of a query shape scans every table once; after that the query reads an immutable list of its tables, and a new table is added to the lists it matches when it is created. Readers never lock. See [Architecture](https://ecs.xgamedev.net/en/docs/architecture#query-cache). ## Warm-up The first updates of a world, which create the tables, the query cache entries and the buffers that later updates reuse. After warm-up, queries, iteration, component access and structural changes allocate nothing, so an allocation test runs one update before it counts bytes. See [Testing systems](https://ecs.xgamedev.net/en/docs/guide/testing#allocations). ## System A class deriving from `EcsSystem` with one job. Its `[ForEach]` methods run over every matching entity on each update; it keeps no state of its own and never calls another system. See [Systems](https://ecs.xgamedev.net/en/docs/guide/systems). ## System group A struct implementing `ISystemGroup`. Systems marked `[UpdateInGroup]` run only on `world.Update()`, so input, simulation and persistence can run at their own cadence. Systems without the attribute are in the default group, which `world.Update()` runs. A group can filter the entities of all its systems: `[With]`, `[Without]` and `[WithAny]` on the group struct, or `IGroupWith` / `IGroupWithout` implemented by the group or an interface it implements (the way a generic interface gives each actor type its own group). See [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#system-groups). ## Update and tick An update is one call of `world.Update()` (or `world.Update()`): every enabled system of the group runs once, in order, unless its `UpdateInterval` skips this update. A tick is one step of the simulation at a fixed rate; a server's loop calls `Update()` once per tick. See [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#one-update). ## Stage A run of consecutive systems with no order and no conflicting [access](https://ecs.xgamedev.net/en/docs/glossary#access-set) between them. With `WorldOptions.ParallelSystems`, a stage's systems run at the same time; without it, every system is its own stage. See [Threading](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems). ## Access set What a system reads and writes, generated from its `[ForEach]` parameters: a `ref` component or singleton is a write, an `in` one a read, and `[Changed]` or `[Removed]` reads `T`. Two systems conflict when one writes what the other reads or writes. A system that can reach the whole world (an `Entity` or `World` parameter, an instance method, an `OnUpdate` override) runs alone. Only systems that do not conflict share a [stage](https://ecs.xgamedev.net/en/docs/glossary#stage). See [Threading](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems). ## Runner What runs parallel work for a world: the systems of a stage, or the chunks of a parallel method. The calling thread works through the items together with up to `WorldOptions.MaxDegreeOfParallelism - 1` reusable thread-pool work items, so a parallel run allocates nothing. It wakes those helpers only while measured runs show they make the work faster; a busy runner leaves the items to the calling thread. See [Threading](https://ecs.xgamedev.net/en/docs/guide/threading#parallel-systems). ## Chunk A slice of the matching rows of a parallel method (`[ForEach(Parallel = true)]`, `ForEachParallel`): a multiple of 64 rows, about four per thread, between 1,024 and 16,384 rows. The [runner](https://ecs.xgamedev.net/en/docs/glossary#runner) hands the chunks to its threads; fewer than two chunks run on the calling thread alone. See [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#parallel-methods). ## Struct job A struct implementing `IForEach`, `IForEachEntity` or `IForEachBatch` whose `Execute` method the row loop calls. The JIT inlines it, so there is no delegate and no virtual call per entity. The generator writes one for every `[ForEach]` method. `entity.Run(ref job)` runs an `IForEachEntity` job on one entity. A job's `static int Writes` names the components it writes; implementing `INoStructuralChanges` promises no structural change. See [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries#foreach-a-struct-job). ## Batch method A `[ForEach]` method whose component parameters are spans (`Span`, `ReadOnlySpan`). It receives runs of consecutive matching rows, element `i` of every span being the same entity, and a whole table in one call when every row matches; an `EntitySpan` parameter gives the entities of the run. The spans point into the tables, so the structure is [frozen](https://ecs.xgamedev.net/en/docs/glossary#frozen-structure) while it runs. Write one to vectorize a loop. See [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#batch-methods). ## Optional component (`Maybe`) A `[ForEach]` parameter for a component the entity may lack: the method visits every entity with its other components, and `HasValue` says whether this one also has `T`. See [Systems](https://ecs.xgamedev.net/en/docs/guide/systems#maybe). ## Change tick A counter of the world (`world.ChangeTick`) that grows once per stage and once after each update. Tracked rows record the tick of their last write, and each system records the tick it last ran at (`LastRunTick`). See [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking#ticks). ## Tracked component A component that also implements `ITrackChanges`. Its rows record when they were written or removed, so `[Changed]` and `[Removed]` visit only those rows. It costs 8 bytes per row; untracked components pay nothing. See [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking). ## Structural change Anything that changes which components an entity has, or which entities exist: create, destroy, `Set` of a new component, `Remove`, `Disable`. In EasyEcs it applies at once, even in the middle of a pass, with no command buffer. See [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes). ## Pass One walk over the matching rows: a run of a `[ForEach]` method, a `ForEach` job or a `Query` loop. A pass visits each entity at most once, skips the entities that stop matching before their turn, and does not visit the ones that join a matching table during it. See [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes#during-a-pass). ## Tombstone The row an entity leaves when it is destroyed or moves to another table during a [pass](https://ecs.xgamedev.net/en/docs/glossary#pass). Outside a pass, the table's last row fills the hole at once; during one, the row stays as a tombstone that passes skip, so no row shifts under a loop. The last pass to end closes the tombstones by moving live rows into them. This is why you can destroy or remove while iterating, with no command buffer. See [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes#keeping-tables-dense). ## Frozen structure A pass that holds refs or spans into the tables for longer than one call freezes the world's structure while it runs: [batch methods](https://ecs.xgamedev.net/en/docs/glossary#batch-method), jobs that implement `INoStructuralChanges`, parallel methods and parallel stages. A structural change inside one throws `InvalidOperationException`. See [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes#frozen-passes). ## Structural gate The check every structural change passes through (`World.Structural()`, internal to EasyEcs). Structural changes belong to the [owner thread](https://ecs.xgamedev.net/en/docs/glossary#owner-thread), so the gate is a plain flag the owner sets and clears, with no atomic instruction. It throws `InvalidOperationException` when a change is reentered from code running under the gate, or made while the structure is [frozen](https://ecs.xgamedev.net/en/docs/glossary#frozen-structure), instead of tearing the tables. It cannot see every change made from another thread at the same moment; the analyzer reports the ones it can (EECS013, EECS014). See [Threading](https://ecs.xgamedev.net/en/docs/guide/threading#what-the-world-synchronizes). ## Owner thread The thread that calls a world's `Update` and makes its structural changes. A world has one at a time; a server runs one world per thread and hands input to it through a [mailbox](https://ecs.xgamedev.net/en/docs/glossary#mailbox). See [Threading](https://ecs.xgamedev.net/en/docs/guide/threading#terms-process-world-owner-thread). ## Mailbox A queue your code owns that carries input from other threads (network, timers, a database) to a world's owner thread. EasyEcs has none of its own: other threads post messages, and a system on the owner thread takes them and turns each into data, such as a request entity. See [Threading](https://ecs.xgamedev.net/en/docs/guide/threading#input-from-other-threads). ## Actor A pattern, not an EasyEcs type: an entity that handles messages addressed to it by key (a shop, a bank account, a player). One type per kind of actor is at once its key component (`IIndexed`, found through its index), its system group and the group's filter (`IGroupWith>`), declared once through a generic interface; a request runs on its entity with `entity.Run`. See [samples/Actors](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/Actors). ## Prefab A recipe of component values that belongs to no world (`new Prefab().SetHealth(30)`), so no query ever sees it. `world.Instantiate(prefab)` creates an entity, or a wave, with a copy of every value. See [Prefabs](https://ecs.xgamedev.net/en/docs/guide/prefabs). ## Dynamic buffer A `DynamicBuffer` component: a list that belongs to one entity, such as a bag of loot or a path. Its writes need a `ref`, so every change is tracked, and snapshots copy its elements. See [Dynamic buffers](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers). ## Value index A lookup from a key to the entities whose component has that key: `IIndexed` on the component, `world.Index()` to query it. The index follows every `Set`; a comparable key also gives sorted ranges. See [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations). ## Relation A link from one entity to another. One link per entity is a component indexed by an `EntityId`; many links of one kind per entity are `IRelation` elements of a buffer. Both answer "who links to this entity?". See [Indexes and relations](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations). ## Hierarchy Parent and child entities linked by the built-in `ChildOf` component. `world.Children(parent)` lists the children, `world.Descendants(root)` walks the whole subtree depth first, and destroying a parent destroys its descendants. See [Hierarchy](https://ecs.xgamedev.net/en/docs/guide/hierarchy). ## Group (IGroup) A component implementing `IGroup` whose value splits tables after `world.GroupBy()`: the entities of one zone, map or match share tables, so a query of that group walks only its rows. Not to be confused with a [system group](https://ecs.xgamedev.net/en/docs/glossary#system-group). See [Groups](https://ecs.xgamedev.net/en/docs/guide/groups). ## Cleanup component A component implementing `ICleanupComponent`. Destroying its entity removes the other components and adds the `Destroyed` tag; the entity stays until a system releases the resource (a socket, a seat) and removes the component. See [Cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable#cleanup-components). ## Disabled component A component hidden by `entity.Disable()`: the value stays, but queries, `Has` and `Get` act as if the entity lacked it until `Enable()`. The entity carries the `Disabled` tag meanwhile, which queries can ask for. See [Cleanup and disable](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable#disable-a-component). ## Snapshot An in-memory copy of a world: `world.Capture()` takes one, `world.Restore(snapshot)` rolls back to it. Used for undo, rollback and resetting a world between tests. See [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots). ## Save A world, or some of its entities, written as bytes: `world.Save` and `world.Load`. Unmanaged components are written as raw rows, managed ones through Nino (`[NinoType]`). See [Saves](https://ecs.xgamedev.net/en/docs/guide/saves). ## Migration Moving a group of entities, such as a player and what it owns, to another world: `SaveEntities` and `LoadEntities` through bytes (another process), or `MoveEntities` directly (another world of the thread). Links inside the group follow the new ids. A record saves only what persists: `SaveEntities` with a `ComponentSet`, loaded onto entities that exist already with `LoadEntitiesInto` (`markWritten: false` keeps the restored values from counting as changed). See [Migration and unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload). ## Collectible ALC A collectible `AssemblyLoadContext`: .NET's way to load a plugin and unload it later. `world.RemoveTypes(context)` removes the plugin's systems, components and singletons from a world, so the context can unload while the world keeps running. See [Migration and unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload). ## Related - [Entities and components](https://ecs.xgamedev.net/en/docs/guide/entities-and-components): Handles, ids, components, tags and where they are stored. - [Systems](https://ecs.xgamedev.net/en/docs/guide/systems): `[ForEach]`, batch and parallel methods, groups, ordering and intervals. - [Threading](https://ecs.xgamedev.net/en/docs/guide/threading): The owner thread, stages, the runner and input from other threads. - [Change tracking](https://ecs.xgamedev.net/en/docs/guide/change-tracking): Change ticks, `[Changed]` and `[Removed]`. --- # Performance guide > How fast EasyEcs is and how to keep your code fast: measured server ticks, the cost of each iteration API, a checklist and every BenchmarkDotNet result. URL: https://ecs.xgamedev.net/en/docs/performance Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/performance.md EasyEcs is built for a server tick that runs every few milliseconds for months: the regular way of writing a system is already a generated, inlined struct job, and a busy world allocates nothing per tick. This page shows what that costs on a real tick, which API to pick for each loop, the rewrites that pay when a system shows up in your timings, and every benchmark behind those numbers. How the library gets there is on [Why EasyEcs is fast](https://ecs.xgamedev.net/en/docs/why-fast). - Save 10,000 entities and load them back, vs DefaultEcs: **30× faster**, EasyEcs 146 μs, DefaultEcs 4.33 ms - One server tick: **1.72 ms**, 100,000 entities in one world - Four worlds, one thread each: **924 μs**, 4 × 25,000 entities - Allocated per tick: **0 B**, after warm-up; the unit tests fail the build otherwise BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## The headline ticks `WorldSimulationBenchmark` is one tick of a busy MMO-style world, not a toy loop: 30% players, 70% NPCs and projectiles on top. One tick runs movement (skipping `Stunned` and `Dead`), an area-of-interest grid, combat that adds `Burning` and `Stunned` at random, status expiry that removes them, death (a `Dead` tag and a statistics singleton), respawn (dead NPCs replaced, dead players revived in place), and projectiles spawned by about 5% of the players and expired after 20 ticks. Setup checks that the world is busy: hits, deaths, spawns and grid changes all happen. **100,000 entities** | Benchmark | What it runs | Time per tick | Allocated per tick | | -------------------------- | ------------------------------------------------------------------------------------ | ------------- | ------------------ | | `WorldSimulationBenchmark` | one world, 100,000 entities | 1.72 ms | 0 B | | `MultiWorldBenchmark` | four worlds of 25,000, one thread each | 924 μs | 0 B | | `BattleServerBenchmark` | the [battle server](https://ecs.xgamedev.net/en/docs/example): every feature at once | 2.97 ms | 0 B | **10,000 entities** | Benchmark | What it runs | Time per tick | Allocated per tick | | -------------------------- | -------------------------- | ------------- | ------------------ | | `WorldSimulationBenchmark` | one world, 10,000 entities | 158 μs | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The four worlds of `MultiWorldBenchmark` are the layout recommended for a server: one world per map or zone, each owned by one long-lived thread. ## Against other libraries The same work ported to Friflo.Engine.ECS, Arch and DefaultEcs, each library its own idiomatic way, with identical results checked in setup: EasyEcs is faster in 24 of 37 head-to-head benchmarks and within the measurement error in 11 more. These are its biggest leads over the fastest other library: | What is measured | EasyEcs | Next fastest | Its time vs EasyEcs | The others | | ------------------------------------------------------------------------------------------------------------------------------ | ------- | ------------------------------------- | ------------------- | ---------------------------------------------------------- | | [Save 10,000 entities and load them back](https://ecs.xgamedev.net/en/docs/comparison#saves) | 146 μs | DefaultEcs 4.33 ms, 4.37 MB allocated | 30× | Friflo.Engine.ECS 143×, 6.52 MB allocated | | [Add a component to 100,000 entities by query, then remove it](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 78.7 μs | Arch 1.21 ms | 15× | DefaultEcs 103×; Friflo.Engine.ECS 154×, 4.00 MB allocated | | [Spawn 10,000 entities beside 100,000, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 138 μs | Friflo.Engine.ECS 380 μs | 2.75× | Arch 2.96×; DefaultEcs 9.7×, 313 KB allocated | | [Query 100,000 players by value: a rating range, zone sums](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 127 μs | Friflo.Engine.ECS 317 μs | 2.49× | — | | [Create 1,000 parent-child squads, destroy them in cascade](https://ecs.xgamedev.net/en/docs/comparison#hierarchy) | 452 μs | Friflo.Engine.ECS 1.06 ms | 2.35× | — | | [Count 100 inventories through an index (1 item traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 425 ns | DefaultEcs 838 ns | 1.97× | Friflo.Engine.ECS 3.2× | | [Add a status component to 5% of 100,000 entities, then remove it](https://ecs.xgamedev.net/en/docs/comparison#operations) | 517 μs | Friflo.Engine.ECS 1.00 ms | 1.94× | — | | [Find the 10 of 100,000 entities written this tick](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | 507 ns | Arch 966 ns | 1.91× | Friflo.Engine.ECS 2.85×; DefaultEcs 73× | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The full server tick is closer, because most of a tick is iteration over dense columns, bound by memory more than by the library: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Every comparison, sorted by lead, with the ones where another library is faster and why: [Comparison](https://ecs.xgamedev.net/en/docs/comparison#feature-by-feature). ## Creating entities in a fresh world A server creates most of its entities in a world that has never held any: at start-up, or when it opens a map or a match. `ColdCreateComparison` measures that moment: 100,000 entities of one, two or three components created in a new world of each library, a new world for every call, three ways: - **`PerEntity`**: one `CreateEntity` per entity, nothing reserved. - **`PerEntity_Reserved`**: the same loop after reserving room for all of them: `world.EnsureCapacity(n)` in EasyEcs, `EnsureCapacity` on the store and the archetype in Friflo, `EnsureCapacity` with the signature in Arch. DefaultEcs has no reservation per component set. - **`Bulk`**: one `world.CreateEntities(span, values)` call. Only EasyEcs runs this case; the comparisons count each other library's fastest way against it. **1 component** **Create 100,000 entities of one component in a fresh world** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------------ | ------- | ---------- | --------- | | EasyEcs | PerEntity | 5.99 ms | 1.00× | 6.97 MB | | Friflo.Engine.ECS | PerEntity | 15.3 ms | 2.56× | 7.99 MB | | Arch | PerEntity | 3.76 ms | 0.63× | 4.00 MB | | DefaultEcs | PerEntity | 13.1 ms | 2.19× | 11.1 MB | | EasyEcs | PerEntity_Reserved | 1.94 ms | 1.00× | 2.67 MB | | Friflo.Engine.ECS | PerEntity_Reserved | 11.3 ms | 5.8× | 3.29 MB | | Arch | PerEntity_Reserved | 3.45 ms | 1.78× | 3.85 MB | | EasyEcs | Bulk | 2.65 ms | 1.00× | 4.20 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **2 components** **Create 100,000 entities of two components in a fresh world** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------------ | ------- | ---------- | --------- | | EasyEcs | PerEntity | 6.35 ms | 1.00× | 7.97 MB | | Friflo.Engine.ECS | PerEntity | 14.1 ms | 2.22× | 8.99 MB | | Arch | PerEntity | 4.61 ms | 0.73× | 4.43 MB | | DefaultEcs | PerEntity | 15.0 ms | 2.36× | 15.1 MB | | EasyEcs | PerEntity_Reserved | 2.71 ms | 1.00× | 3.05 MB | | Friflo.Engine.ECS | PerEntity_Reserved | 12.2 ms | 4.5× | 3.80 MB | | Arch | PerEntity_Reserved | 3.77 ms | 1.39× | 4.24 MB | | EasyEcs | Bulk | 2.55 ms | 1.00× | 4.58 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **3 components** **Create 100,000 entities of three components in a fresh world** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------------ | ------- | ---------- | --------- | | EasyEcs | PerEntity | 7.13 ms | 1.00× | 8.97 MB | | Friflo.Engine.ECS | PerEntity | 15.4 ms | 2.15× | 9.99 MB | | Arch | PerEntity | 4.77 ms | 0.67× | 4.84 MB | | DefaultEcs | PerEntity | 16.9 ms | 2.38× | 19.1 MB | | EasyEcs | PerEntity_Reserved | 2.60 ms | 1.00× | 3.44 MB | | Friflo.Engine.ECS | PerEntity_Reserved | 12.3 ms | 4.7× | 4.30 MB | | Arch | PerEntity_Reserved | 4.21 ms | 1.62× | 4.62 MB | | EasyEcs | Bulk | 2.71 ms | 1.00× | 4.96 MB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Pre-sized or in one call, EasyEcs is the fastest of the four.** With three components, the reserved loop takes 2.60 ms and one `CreateEntities` call 2.71 ms; Arch, the next fastest, takes 4.21 ms reserved, 1.62× as long. **One by one with nothing reserved, Arch is faster.** EasyEcs takes 7.13 ms, 1.50× as long as Arch's 4.77 ms. Without a reservation, a fresh table grows by doubling, and so does the entity storage. Their arrays past 85,000 bytes go to the large object heap, and once the allocations there pass the runtime's budget, .NET starts a full collection: one per new world in this benchmark, and most of the difference. Arch keeps entities in chunks of 16 KB, small objects that never reach that heap. Friflo and DefaultEcs pay the collection too and stay slower than EasyEcs. A reservation sizes the table and the entity storage once and puts the entity records on the pinned object heap, so the run stays under both budgets and no collection starts ([D28](https://ecs.xgamedev.net/en/docs/decisions#d28-reservations-grow-to-what-they-need-entity-storage-on-the-pinned-heap)); the loop without it takes 2.75× as long. So when you know how many entities a world is about to get, say so: ```csharp // The table of exactly these components, sized for the whole start-up world.EnsureCapacity(100_000); for (int i = 0; i < 100_000; i++) world.CreateEntity(new Position(i, 0), new Velocity(1, 0), new Health(100)); ``` Entities that start with the same values can also come in one call, which sizes the table from the span and hands you the handles: ```csharp var garrison = new Entity[100_000]; world.CreateEntities(garrison, new Position(0, 0), new Velocity(0, 0), new Health(100)); ``` Only the first fill of a world pays the growth. A world that already has the room creates and destroys at full speed: `CreateDestroy` in the [single operations](https://ecs.xgamedev.net/en/docs/comparison#operations). BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Choosing an iteration API Every API walks the same tables front to back. What differs is the bookkeeping around each row: a delegate call, an enumerator, a structural-change check. Pick the first row that fits: | Need | Use | Measured | | --------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------- | | The per-entity logic of a system | a [`[ForEach]` method](https://ecs.xgamedev.net/en/docs/guide/systems) | 0.91 ns per entity, against 1.28 ns for two plain arrays | | Arithmetic over many rows | a batch `[ForEach]` method (spans), vectorized | 69.5 μs instead of 253 μs per-entity (100,000 entities) | | Heavy per-entity work | `[ForEach(Parallel = true)]` | 884 μs instead of 1.68 ms (100,000 entities, 4 cores) | | A loop outside systems, every tick | a static `[ForEach]` method run through its entry point, or a struct job (`world.ForEach`) | 33.7 μs, against 145 μs for a `Query` loop | | A loop in a tool, a test or a request handler | `foreach (var item in world.Query<...>())` | 30.5 μs, against 12.9 μs for a struct job (10,000 entities) | | "How many?" / "Is there any?" | `world.Count` / `world.Any` | 1.20 μs for 100,000 rows whose bits must be tested | | The few rows written since the last run | `ITrackChanges` + `[Changed]` | 525 ns instead of 38.6 μs (10 of 100,000 written) | | The entities that lost a component | `ITrackChanges` + `[Removed]` | 830 ns (10 of 100,000 removed) | | Entities by value | a [value index](https://ecs.xgamedev.net/en/docs/guide/indexes-and-relations) | see `IndexBenchmark` [below](https://ecs.xgamedev.net/en/docs/performance#benchmarks) | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. `[ForEach]` beats two plain arrays because its columns start on a 64-byte boundary: a row of a power-of-two-sized component never straddles two cache lines. `MicroBenchmarks.ForEachSystemWrite` runs on a world with one table; the other iteration rows of `MicroBenchmarks` use a world where every other entity also has `Health` (two tables), so compare APIs within one world, not across them. ## Regular code and the fastest code The regular way is right for most systems: short, and already a generated struct job. When a system shows up in `WorldOptions.MeasureSystems` timings ([measuring systems](https://ecs.xgamedev.net/en/docs/guide/systems#measuring-systems)), these rewrites are what the benchmarks measure: | Regular | Fastest | Measured | | --------------------------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------------------- | | A per-entity `[ForEach]` doing arithmetic with branches | A batch method vectorized with `Vector`, branches as masks | 253 μs → 69.5 μs | | `foreach (var item in world.Query<...>())` in a hot ad-hoc loop | A struct job with `world.ForEach` | 30.5 μs → 12.9 μs | | A `bool` flag tested in every row | A tag with `[With]` / `[Without]` | rows without the tag skipped 64 at a time; toggling flips a bit | | Scanning every row for the few that changed | `ITrackChanges` + `[Changed]` | 38.6 μs → 525 ns | | `CreateEntity` / `Destroy` in a loop | `CreateEntities` / `DestroyEntities`, `Instantiate(prefab, span)` | 334 μs → 157 μs | | Setting a component on every entity one by one | `world.SetAll` / `RemoveAll` | 1.68 ms → 87.9 μs | | One method taking `Maybe` | Two methods split by `[With]` / `[Without]` | 130 μs → 41.8 μs | | A `QueryFilter` built at the call | A `static readonly` filter | 74.8 ns → 21.6 ns per call | | Heavy per-entity work on one thread | `[ForEach(Parallel = true)]` | 1.68 ms → 884 μs | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Arithmetic over many rows: vectorize a batch method The JIT does not vectorize this loop, and the bounce branches mispredict on many rows. The regular system: ```csharp public class BounceSystem : EcsSystem { [ForEach, Without] static void Move(ref Position p, ref Velocity v) { p = new Position(p.X + v.X, p.Y + v.Y); if (p.X < 0 || p.X > 4096) v = v with { X = -v.X }; if (p.Y < 0 || p.Y > 4096) v = v with { Y = -v.Y }; } } ``` The fastest one takes spans (runs of consecutive rows; a table whose rows all match is one call), reads the two-float components as one float span (X, Y, X, Y, ...) so every lane of a `Vector` is one coordinate, and turns the branches into a mask: ```csharp using System.Numerics; using System.Runtime.InteropServices; public class BounceSimdSystem : EcsSystem { [ForEach, Without] static void Move(Span positions, Span velocities) { var p = MemoryMarshal.Cast(positions); var v = MemoryMarshal.Cast(velocities); var max = new Vector(4096f); int i = 0; for (; i <= p.Length - Vector.Count; i += Vector.Count) { var velocity = new Vector(v[i..]); var position = new Vector(p[i..]) + velocity; var outside = Vector.LessThan(position, Vector.Zero) | Vector.GreaterThan(position, max); position.CopyTo(p[i..]); Vector.ConditionalSelect(outside, -velocity, velocity).CopyTo(v[i..]); } for (; i < p.Length; i++) // the rows left over { p[i] += v[i]; if (p[i] < 0 || p[i] > 4096) v[i] = -v[i]; } } } ``` The cast is valid because the components hold only floats (no padding, no references), and unmanaged columns start on a 64-byte boundary, so vector loads stay aligned. A batch method makes no structural change and reads entities through an `EntitySpan` parameter only where it needs them. A scalar loop over spans gains little over the per-entity method: write one to vectorize it. **Movement over 100,000 entities: per entity and vectorized** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------ | ------- | ---------- | --------- | | EasyEcs | Iterate2 | 253 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2 | 257 μs | 1.02× | 0 B | | EasyEcs | Iterate2Simd | 69.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2Simd | 80.7 μs | 1.16× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Ad-hoc loops: a struct job `world.Query` is the convenient loop for tools and request handlers. For a loop that runs every tick outside a system, write a struct job: `world.ForEach` specializes and inlines it per table. Mark it `INoStructuralChanges` and declare its `Writes` ([what a job declares](https://ecs.xgamedev.net/en/docs/guide/queries)). ```csharp public struct EnergyJob : IForEach, INoStructuralChanges // no structural change: the lean loop { public float Total; // a value field stays in a register during the pass and is copied back once public static int Writes => 0; // reads only: no row counts as changed public void Execute(ref Velocity v) => Total += v.X * v.X + v.Y * v.Y; } ``` ```csharp var job = new EnergyJob(); world.ForEach(ref job); float energy = job.Total; ``` Declare the job a `ref struct` when it must hold a `ref` or a `Span` (an output buffer, a caller's array). `ForEach`, `ForEachEntity` and `ForEachBatch` accept ref struct jobs; the `*Parallel` calls do not, because each thread gets its own copy of the job. For a total, a value field is faster than a `ref` field: a write through a `ref` goes to memory on every row. ```csharp public ref struct CollectJob : IForEach, INoStructuralChanges { public Span Xs; // the caller's buffer, at least as long as the matching rows public int Count; public static int Writes => 0; public void Execute(ref Position p) => Xs[Count++] = p.X; } ``` A static `[ForEach]` method outside a system does the same with less code: the generator writes the job and an entry point that takes the world (`RunnerBenchmark` measures both). ```csharp public static class Census { [ForEach, Without] static void CountWounded(in Health health, ref int wounded) { if (health.Value < 50) wounded++; } } ``` ```csharp int wounded = 0; Census.CountWounded(world, ref wounded); // generated entry point: the job runs once ``` ### States: tags, not flags A flag costs a load and a branch in every row of every system that checks it. A tag is a filter: rows without it are skipped 64 at a time, and adding or removing it flips a presence bit while the entity keeps its row. ```csharp public record struct Unit(int Hp, bool Stunned) : IComponent; // regular: every system tests the flag public class StunnedFlagSystem : EcsSystem { [ForEach] static void Act(ref Unit unit) { if (unit.Stunned) return; unit.Hp++; } } public class StunnedTagSystem : EcsSystem // fastest: the filter does the test { [ForEach, Without] static void Act(ref Health hp) => hp = hp with { Value = hp.Value + 1 }; } ``` Toggling a status is where this shows against other archetype libraries: EasyEcs flips a bit, Friflo moves the entity to another archetype and back. **Stun 5% of 100,000 fighters, then recover them** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------ | ------- | ---------- | --------- | | EasyEcs | Toggle | 517 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Toggle | 1.00 ms | 1.94× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### The few rows that changed: `[Changed]` A replication or persistence system that scans every row pays for the rows nobody wrote. Mark the component `ITrackChanges` and filter with `[Changed]`: unwritten tables, 4,096-row blocks and 64-row words are skipped. Take the component by `in`, so the visit does not count as a write. ```csharp public record struct Shield(int Value) : IComponent, ITrackChanges; public record struct ShieldReplica(int Value) : IComponent; public class ShieldReplicationSystem : EcsSystem { [ForEach, Changed] static void Send(in Shield shield, ref ShieldReplica replica) => replica = new ShieldReplica(shield.Value); } ``` It pays when few rows are written, or when the written rows sit close together: | Rows written of 100,000 | `[Changed]` | Every row | | --------------------------- | -------------- | --------- | | 10 | 525 ns | 38.6 μs | | 1,000, spread 97 rows apart | 38.9 μs | 67.2 μs | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. When writes land in most 64-row words, nothing is skipped and testing the change ticks costs about what reading the column does. For a cheap check over a column that most rows write every tick (a death check on `Health`), a plain scan is as fast and simpler. ### What went away: `[Removed]` Replicating a removal (a fire that went out) with a marker tag costs a structural change per removal and a pass over the tags; comparing every row with what clients last received costs a scan. A tracked component's removal already stamps its row, so `[Removed]` visits only the entities that lost it, with the same skipping as `[Changed]`: ```csharp public class ShieldLossSystem : EcsSystem { [ForEach, Removed] // Shield : ITrackChanges (above) static void Send(ref ShieldReplica replica) => replica = new ShieldReplica(0); } ``` **Find the 10 of 100,000 entities that lost a buff** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------- | ---------- | --------- | | EasyEcs | Removed | 830 ns | 1.00× | 0 B | | DefaultEcs | WhenRemoved | 39.6 μs | 48× | 0 B | | Friflo.Engine.ECS | Event | 697 ns | 0.84× | 0 B | | Arch | LostTag | 1.81 μs | 2.18× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### The entity only where the row needs it An `Entity` parameter builds a handle for every row, even when only a rare branch uses it, and it makes the system run alone in a parallel stage. When the entities a system acts on can be told by a component, filter on it (`[With]`) instead of testing every row. A batch method that needs the entity of a few rows takes an `EntitySpan`, which builds a handle only for the rows it indexes. **A pass over 100,000 entities that rarely needs the entity** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ----------- | ------- | ---------- | --------- | | EasyEcs | Entity | 49.0 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Entity | 67.2 μs | 1.37× | 0 B | | EasyEcs | EntityBatch | 38.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | EntityBatch | 37.0 μs | 0.96× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Waves of entities: bulk calls ```csharp private static readonly Prefab Goblin = new Prefab().SetPosition(0, 0).SetHealth(30); ``` ```csharp var wave = new Entity[1_000]; world.CreateEntities(wave, new Position(0, 0), new Velocity(1, 0)); // one pass through the structural gate world.Instantiate(Goblin, wave); // a wave of a prefab, the same way int removed = world.DestroyEntities(); // every dead entity, one pass int lifted = world.RemoveAll(); // every stun lifted, whole words of rows ``` A [prefab](https://ecs.xgamedev.net/en/docs/guide/prefabs) built once (`static readonly`) costs one row copy per instance; the world finds its target table once and caches it. `entity.Set(a, b)` and `entity.Remove()` change several components in one call: shorter to write, and the same cost as one call per component, since the second move takes a cached transition ([D29](https://ecs.xgamedev.net/en/docs/decisions#d29-performance-rules-only-where-the-cost-is-measured-and-the-fix-does-the-same)). ## Do The checklist for code that runs every tick. Find the system worth the effort first: `WorldOptions.MeasureSystems` times every system run. - **Mutate through refs**: `ref var hp = ref item.Component1;`, `ref var hp = ref entity.Get();`. - **Spawn with every component at once**: `world.CreateEntity(a, b, c)` places the entity in its final table; `world.Instantiate(prefab)` for a kind defined once. `entity.Set(a, b)` / `entity.Remove()` change several components in one call: shorter, with the same cost as one call each. - **Read with `in`, write with `ref`**: `in` parameters, `entity.Read()` or the generated property read; `ref` parameters and `entity.Get()` write. A `ref` access counts as a write of a tracked component, and a `Query` loop counts every row it visits; a struct job that only reads declares `static int Writes => 0`. - **Keep `[ForEach]` methods that make no structural change `static`**, without a `World` parameter and with read-only use of their `Entity`: the generator marks their job `INoStructuralChanges`, which skips the per-row bookkeeping. Mark hand-written jobs the same way. - **Take singletons as `[ForEach]` parameters** (resolved once per pass), or keep a `SingletonRef` outside systems (no lookup per access). - **Give systems a cadence**: `UpdateInterval`, or a system group updated when needed (`Update()`), instead of a counter checked in the method. - **Keep components small** (a few fields, well under 64 bytes) and split rarely used data into its own component: iteration loads only the columns it reads. - **Vectorize arithmetic in batch methods**, use bulk calls for waves, tags for states, `[Changed]` for what changed and `[Removed]` for what went away ([above](https://ecs.xgamedev.net/en/docs/performance#regular-code-and-the-fastest-code)). - **Ask `world.Count` / `world.Any`** instead of looping to count or to find one match. - **Reserve room** in a `DynamicBuffer` whose size is known (`EnsureCapacity`), and pre-size the world with `WorldOptions.InitialEntityCapacity` or `world.EnsureEntityCapacity(n)`, and a table before creating its entities one by one with `world.EnsureCapacity(n)`. - **Keep `QueryFilter`s in `static readonly` fields** (the generator does this for `[ForEach]`). - **Look entities up with a value index** (`IIndexed`) instead of a dictionary kept in sync by hand, and write an indexed component only when its key changes. - **Run one world per thread** on servers, for example one per map or zone. ## Don't - **Don't modify a copy** of a component and forget to write it back. - **Don't keep `ref`s across `await` or in fields**: keep the `Entity` handle. - **Don't store raw entity indexes**: ids are recycled; store an `EntityId` (index and version). - **Don't write lambdas that capture locals** in methods that run every update: the closure is allocated at method entry even when its branch is not taken. `AllocationTests` caught exactly this in `World.Update` ([EECS028](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs028)). - **Don't use LINQ, `params object[]` or string formatting** in per-update code ([EECS028](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs028)). - **Don't take an `Entity` or a singleton parameter a method does not need**: the loop loads it for every row ([EECS026](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs026)). - **Don't take a tracked component by `ref` when the method only reads it**: every visited row then counts as changed ([EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025)). - **Don't look up the visited entity's components or a singleton inside a `[ForEach]` method**: a parameter resolves them once per table ([EECS027](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs027)). - **Don't make a `[ForEach]` method an instance method when it uses nothing of its system**: it then runs alone and pays the checks of a structural change ([EECS029](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs029)). - **Don't loop over a query to change, count or test entities one by one**: `SetAll`, `DestroyEntities`, `Count`, `Any` and filters do it per table ([EECS030](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs030), [EECS032](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs032)). - **Don't use a value index, or destroy entities, from another thread**: the index follows those changes on the owner thread and is not synchronized. ## Pitfalls | Mistake | What happens | Caught by | | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | A batch method that also takes a per-entity parameter | It cannot receive runs of rows | [EECS009](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs009) | | A structural change in a static `[ForEach]` method without `Entity` or `World` | The method promises no structural change, and its lean loop relies on it | [EECS013](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs013) | | A parallel method that writes a singleton or changes structure | Data races between the threads | [EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs010) | | An `Entity` stored in a component | The column holds references: no longer pinned, scanned by the GC | [EECS017](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs017) (warning) | | Writing an indexed component through a `ref` | The index cannot see the new key | [EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs015) | | A computed `UpdateInterval` | Read every update | [EECS018](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs018) (warning) | | A `ref` parameter that only reads a tracked component | Every visited row counts as changed | [EECS025](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs025) (warning, code fix: `in`) | | A closure or LINQ in per-update code | Garbage every tick | [EECS028](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs028) (warning), and `AllocationTests`-style checks in your own tests | | A lookup through the visited `Entity` in a `[ForEach]` method | A search per row | [EECS027](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs027) (warning) | | A structural change entity by entity over a query | One row moved per call | [EECS030](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs030) (warning, code fix: the bulk call) | | Filling a fresh world one entity at a time, nothing reserved | Doubling arrays on the large object heap start a full collection ([above](https://ecs.xgamedev.net/en/docs/performance#cold-create)) | [EECS031](https://ecs.xgamedev.net/en/docs/guide/analyzer#eecs031) (warning, code fix: `CreateEntities` or `EnsureCapacity(n)`) | ## What is covered Every feature has unit tests (`tests/EasyEcs.UnitTest`), a BenchmarkDotNet benchmark and, where a peer library has the feature, a head-to-head comparison that checks every library computes the same result before it measures. | Feature | Tests | Benchmark | Against other libraries | | ------------------------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | | A whole server tick | `BattleServerTests` | `WorldSimulationBenchmark`, `MultiWorldBenchmark`, `BattleServerBenchmark` | [`EcsComparisonBenchmark`](https://ecs.xgamedev.net/en/docs/comparison#the-same-server-tick) | | `[ForEach]`, struct jobs, `Query` | `ForEachSystemTests`, `QueryTests`, `RunnerTests` | `MicroBenchmarks`, `RunnerBenchmark`, `CallSiteBenchmark` | [`OperationBenchmark`](https://ecs.xgamedev.net/en/docs/comparison#operations) | | Structural changes, presence bits | `EntityTests`, `ComponentTests`, `PresenceTests` | `MicroBenchmarks` (`Churn`, `ToggleComponent`), `SparseBenchmark`, `CountBenchmark` | [`StructuralChangeComparison`](https://ecs.xgamedev.net/en/docs/comparison#structural-changes) | | Bulk changes and spawns | `BulkTests` | `BulkBenchmark`, `MicroBenchmarks.ChurnBatch` | [`BulkChangeComparison`, `BulkSpawnComparison`](https://ecs.xgamedev.net/en/docs/comparison#bulk) | | Prefabs and clones | `InstantiateTests` | `PrefabBenchmark` | [`OperationBenchmark` (`Instantiate`)](https://ecs.xgamedev.net/en/docs/comparison#operations) | | Change tracking | `ChangedTests` | `ChangeTrackingBenchmark` | [`ChangeTrackingComparison`](https://ecs.xgamedev.net/en/docs/comparison#change-tracking) | | Removal detection | `RemovedTests` | `BattleServerBenchmark` | [`RemovalComparison`](https://ecs.xgamedev.net/en/docs/comparison#removal-detection) | | Disabling | `DisableTests` | `BulkBenchmark` (`DisableAll`) | [`DisableComparison`](https://ecs.xgamedev.net/en/docs/comparison#disabling) | | Value indexes, ordered indexes | `IndexTests`, `OrderedIndexTests` | `IndexBenchmark`, `OrderedIndexBenchmark` | [`IndexComparison`, `ValueQueryComparison`](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | | Relations | `RelationTests`, `TargetPolicyTests` | `RelationBenchmark` | [`RelationComparison`](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | | Hierarchy | `HierarchyTests` | `HierarchyBenchmark` | [`HierarchyComparison`](https://ecs.xgamedev.net/en/docs/comparison#hierarchy) | | Groups | `GroupTests` | `GroupBenchmark` | [`ValueQueryComparison`](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | | Singletons | `SingletonTests` | `MicroBenchmarks.SingletonAccess` | [`OperationBenchmark` (`Singleton`)](https://ecs.xgamedev.net/en/docs/comparison#operations) | | Optional components (`Maybe`) | `ForEachSystemTests` | `MaybeBenchmark` | — | | Dynamic buffers | `DynamicBufferTests` | `DynamicBufferBenchmark` | — | | Cleanup components | `CleanupTests` | `CleanupBenchmark` | — | | System ordering and groups | `SystemTests` | `OrderingBenchmark` | — | | Parallel systems and `[ForEach(Parallel = true)]` | `ParallelTests`, `ConcurrencyTests` | `ParallelSystemsBenchmark`, `ParallelForEachBenchmark` | [`ParallelSystemsComparison`, `ParallelQueryComparison`](https://ecs.xgamedev.net/en/docs/comparison#parallel) | | Snapshots | `SnapshotTests` | `SnapshotBenchmark` (`Capture`, `Restore`) | — | | Saves | `SerializationTests` | `SnapshotBenchmark` (`Save`, `Load`) | [`SaveComparison`](https://ecs.xgamedev.net/en/docs/comparison#saves) | | Moving entities between worlds | `MoveTests` | `MigrationBenchmark` | — | | Unloading a plugin's types | `UnloadTests` | `UnloadBenchmark` | — | | Introspection | `IntrospectionTests` | `IntrospectionBenchmark` | — | | Generic systems | `GenericTests` | — | — | | Generator, analyzer, code fixes | `GeneratorTests`, `CodeFixTests` | — | — | | Zero allocation | `AllocationTests` (0 B budget on every test run) | the Allocated column of every benchmark | every comparison | ## Benchmarks Every class of `benchmarks/EasyEcs.Benchmark`, from one full run. Bars are EasyEcs; the ratio is against the class's baseline, the first way of doing the job. The comparisons with other libraries are on [the comparison page](https://ecs.xgamedev.net/en/docs/comparison). ### Server ticks `WorldSimulationBenchmark` and `MultiWorldBenchmark` are the headline world above. `BattleServerBenchmark` is one tick of the [battle server](https://ecs.xgamedev.net/en/docs/example) (`BattleServer.cs`), which uses every feature: a parallel `[ForEach]`, two systems that run at once, statuses added and removed mid-pass, `WithAny`, deaths, respawns and projectiles, a value index, a relation, prefabs, an update interval, per-system timings and replication every third tick with `[Changed]` and `[Removed]`. `BattleServerTests` checks the same world. | Case | Entities | Mean | vs baseline | Allocated | | ---- | -------- | ------- | ----------- | --------- | | Tick | 10000 | 158 μs | — | 0 B | | Tick | 100000 | 1.72 ms | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ------------- | ------ | ----------- | --------- | | TickAllWorlds | 924 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ---- | ------- | ----------- | --------- | | Tick | 2.97 ms | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Single operations `MicroBenchmarks` isolate one operation each, over 10,000 entities. `RawArrayWrite` is the floor without an ECS: two plain arrays. `HandleAccess`, `TryGetEntity`, `TrackedHandleWrite`, `SingletonAccess` and `CountAndAny` repeat their call 1,000 times. `CreateAddDestroy` builds a fresh world each time, so its allocations are the new world and its growth. **MicroBenchmarks: one operation each, 10,000 entities** | Case | Mean | vs baseline | Allocated | | ------------------ | ------- | ----------- | --------- | | CreateAddDestroy | 1.03 ms | 82× | 1.52 MB | | Churn | 334 μs | 26× | 0 B | | ChurnBatch | 157 μs | 12× | 0 B | | RemoveMany | 51.0 μs | 4.0× | 0 B | | ToggleComponent | 158 μs | 13× | 0 B | | QueryIterate | 30.5 μs | 2.41× | 0 B | | ForEachIterate | 12.9 μs | 1.02× | 0 B | | QueryWrite | 18.9 μs | 1.49× | 0 B | | RawArrayWrite | 12.8 μs | 1.01× | 0 B | | ForEachSystemWrite | 9.13 μs | 0.72× | 0 B | | ForEachWrite | 9.55 μs | 0.75× | 0 B | | QueryIterate3 | 9.71 μs | 0.77× | 0 B | | HandleAccess | 3.33 μs | 0.26× | 0 B | | SingletonAccess | 1.01 μs | 0.08× | 0 B | | TryGetEntity | 3.60 μs | 0.28× | 0 B | | TrackedHandleWrite | 8.37 μs | 0.66× | 0 B | | CountAndAny | 41.1 μs | 3.3× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. `CallSiteBenchmark` measures a query call itself: a filter built at the call, a filter built once, no filter, and a filter past the per-call memo (the query cache's dictionary). `RunnerBenchmark` runs one pass outside systems three ways: a static `[ForEach]` method's entry point, the struct job it replaces written by hand, and a `Query` loop. `OrderingBenchmark` shows that `[UpdateAfter]` costs nothing per update: the order is resolved when systems are added. | Case | Mean | vs baseline | Allocated | | ------------ | ------- | ----------- | --------- | | FilterAtCall | 74.8 ns | 1.00× | 0 B | | FilterOnce | 21.6 ns | 0.29× | 0 B | | NoFilter | 42.9 ns | 0.57× | 0 B | | PastTheMemo | 88.0 ns | 1.18× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | -------------- | ------- | ----------- | --------- | | Runner | 33.7 μs | 1.00× | 0 B | | HandWrittenJob | 56.7 μs | 1.69× | 0 B | | Query | 145 μs | 4.3× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ---------- | ------- | ----------- | --------- | | Registered | 20.9 μs | 1.01× | 0 B | | Ordered | 20.8 μs | 1.01× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Presence bits and filters `SparseBenchmark` keeps 10 burning units among 100,000 in one table (only their presence bits differ): a pass over the few, a query over them, a count of them and a pass over the rest. `CountBenchmark` counts rows that must be tested one by one (two columns with disabled rows), which is vectorized: 8 bit words per step with AVX-512. `MaybeBenchmark` compares one method taking `Maybe` with two methods split by `[With]` / `[Without]`. | Case | Mean | vs baseline | Allocated | | --------------- | ------- | ----------- | --------- | | PassOverTheFew | 386 ns | — | 0 B | | QueryTheFew | 365 ns | — | 0 B | | CountTheFew | 13.6 ns | — | 0 B | | PassOverTheRest | 52.3 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ----- | ------- | ----------- | --------- | | Count | 1.20 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ---------- | ------- | ----------- | --------- | | OneMethod | 130 μs | 1.01× | 0 B | | TwoMethods | 41.8 μs | 0.32× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Structural changes in bulk `BulkBenchmark` stuns 100,000 fighters and lifts the stun, and disables a status for a zone and enables it, each in bulk (`SetAll` / `RemoveAll`, `DisableAll` / `EnableAll`) and entity by entity. `PrefabBenchmark` spawns 1,000 entities from a prefab one by one and as a wave. `CleanupBenchmark` churns 1,000 of 10,000 sessions per operation with a cleanup component against a plain component released by hand. | Case | Mean | vs baseline | Allocated | | -------------------- | ------- | ----------- | --------- | | StunAndLift | 87.9 μs | 1.00× | 0 B | | StunAndLiftEach | 1.68 ms | 19× | 0 B | | DisableAndEnable | 22.9 μs | 0.26× | 0 B | | DisableAndEnableEach | 2.27 ms | 26× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ---------------- | ------- | ----------- | --------- | | InstantiateEach | 49.7 μs | 1.00× | 0 B | | InstantiateBatch | 15.3 μs | 0.31× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ------- | ------- | ----------- | --------- | | Cleanup | 102 μs | 1.00× | 0 B | | Plain | 43.9 μs | 0.43× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Change tracking `ChangeTrackingBenchmark` replicates health: 10 (a quiet tick) or 1,000 of 100,000 entities are written per tick, then one system copies health into a replica with `[Changed]` (`Changed=True`) or by visiting every row. `QueryTick` does the same with an ad-hoc `Query`. `DynamicBufferBenchmark` replicates 1,000 changed bags of 100,000, held as a `DynamicBuffer` or as a `List` in a tracked component. **10 written** | Case | Changed | Mean | vs baseline | Allocated | | --------- | ------- | ------- | ----------- | --------- | | Tick | False | 38.6 μs | — | 0 B | | QueryTick | False | 476 μs | — | 0 B | | Tick | True | 525 ns | — | 0 B | | QueryTick | True | 720 ns | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **1,000 written** | Case | Changed | Mean | vs baseline | Allocated | | --------- | ------- | ------- | ----------- | --------- | | Tick | False | 67.2 μs | — | 0 B | | QueryTick | False | 514 μs | — | 0 B | | Tick | True | 38.9 μs | — | 0 B | | QueryTick | True | 51.0 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | List | Mean | vs baseline | Allocated | | ---- | ----- | ------- | ----------- | --------- | | Tick | False | 56.5 μs | — | 0 B | | Tick | True | 61.8 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The "every row" cases vary from run to run on the reference VM (they depend on how 100,000 rows land in physical memory); the `[Changed]` cases are stable. ### Indexes, relations, groups and hierarchies `IndexBenchmark` uses a relation as an inventory: 100,000 items point at one of 1,000 owners; 100 trades, then 100 inventories counted. `OrderedIndexBenchmark` keeps a leaderboard of 100,000 scores (1,000 change, then the top 10 and one bracket read) against a scan. `GroupBenchmark` sums the players of 4 of 16 zones as a group (a table per zone), a value index and a scan. `RelationBenchmark` rewires 100 of 10,000 friend lists and walks 100 follower sets. `HierarchyBenchmark` destroys 1,000 squad leaders with their members (`ChildOf`, cascade) against links that are only removed. | Case | Mean | vs baseline | Allocated | | ------------- | ------- | ----------- | --------- | | TradeAndCount | 5.28 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ------- | ------- | ----------- | --------- | | Ordered | 75.8 μs | 1.00× | 0 B | | Scan | 307 μs | 4.1× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ----- | ------- | ----------- | --------- | | Group | 47.4 μs | 1.01× | 0 B | | Index | 138 μs | 2.93× | 0 B | | Scan | 742 μs | 16× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | -------------- | ------- | ----------- | --------- | | FollowAndCount | 22.7 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | ----------- | ------ | ----------- | --------- | | Cascade | 590 μs | 1.00× | 0 B | | RemoveLinks | 516 μs | 0.88× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Threads `ParallelSystemsBenchmark` runs four `[ForEach]` systems with disjoint access over 100,000 entities, with `WorldOptions.ParallelSystems` off and on: on, they form one stage and run at once. `ParallelForEachBenchmark` runs one heavy method (steering towards the nearest of 16 waypoints) plain and with `Parallel = true`, and the same work as an ad-hoc job with entity handles (`ForEachEntity` / `ForEachEntityParallel`). | Case | Parallel | Mean | vs baseline | Allocated | | ---- | -------- | ------ | ----------- | --------- | | Tick | False | 420 μs | — | 0 B | | Tick | True | 295 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Parallel | Mean | vs baseline | Allocated | | --------- | -------- | ------- | ----------- | --------- | | Tick | False | 1.68 ms | — | 0 B | | EntityJob | False | 1.92 ms | — | 0 B | | Tick | True | 884 μs | — | 0 B | | EntityJob | True | 896 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The reference machine has 4 cores and the parallel rows carry a large error in this run: read them as "faster on several cores", not as a precise speed-up. ### Snapshots, saves, migration and unloading `SnapshotBenchmark` captures a world of 100,000 entities (two tables, a third of the ids recycled, a singleton) into a new snapshot, restores one in place, saves it as bytes into a reused buffer and loads it back. `Capture` allocates the snapshot it returns; capture into an existing snapshot to reuse it. `MigrationBenchmark` moves 10 players with 99 items each to another world and back, through bytes (`SaveEntities` / `LoadEntities`) and in memory (`MoveEntities`); `SaveAndLoadOne` is the fixed cost of a save. `UnloadBenchmark` removes a plugin's types from a world of 10,000 or 100,000 players (`RemoveTypes`), the step before reloading game logic. | Case | Mean | vs baseline | Allocated | | ------- | ------- | ----------- | --------- | | Capture | 931 μs | — | 2.67 MB | | Restore | 428 μs | — | 0 B | | Save | 262 μs | — | 0 B | | Load | 1.00 ms | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Mean | vs baseline | Allocated | | -------------- | ------- | ----------- | --------- | | SaveAndLoad | 222 μs | 1.00× | 0 B | | Move | 165 μs | 0.74× | 0 B | | SaveAndLoadOne | 2.22 μs | 0.01× | 0 B | | SaveRecord | 104 ns | 0.00× | 0 B | | LoadRecord | 722 ns | 0.00× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. | Case | Players | Mean | vs baseline | Allocated | | ----------- | ------- | ------- | ----------- | --------- | | RemoveTypes | 10000 | 247 μs | — | 2.95 KB | | RemoveTypes | 100000 | 2.38 ms | — | 2.95 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ### Introspection `IntrospectionBenchmark` describes the battle server's world for a dashboard (`world.Describe()`: every table with its columns, rows and bytes) and one entity for a debugger (`entity.Describe()`, values boxed). Both allocate the description they return: they are tools, not tick paths. | Case | Mean | vs baseline | Allocated | | ------ | ------- | ----------- | --------- | | Tables | 10.6 μs | — | 25.0 KB | | Entity | 244 ns | — | 832 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## How to reproduce Numbers come from BenchmarkDotNet only, never from a stopwatch: ```bash dotnet run -c Release --project benchmarks/EasyEcs.Benchmark -- --filter '*' # every class on this page dotnet run -c Release --project benchmarks/EasyEcs.Benchmark -- --filter '*World*' # the headline ticks dotnet run -c Release --project benchmarks/EasyEcs.Comparison -- --filter '*' # other libraries dotnet run -c Release --project benchmarks/EasyEcs.Comparison -- --check # correctness of the ports only ``` Both projects use the job in `benchmarks/EasyEcs.Benchmark/BenchmarkConfig.cs`: 2 launches, 6 warmups, 8 iterations of 250 ms, and call counting from the start (`DOTNET_TC_CallCountingDelayMs=0`) so the warmups reach optimized code. Two processes are measured instead of many iterations of one, because run-to-run differences (code layout, tiering) are larger than the noise within a run. The machine of the numbers on this site: BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. `AllocationTests` guard the zero-allocation contract on every test run (`dotnet test`): the steady-state tick, queries, structural changes, indexes, relations, cascades and parallel passes must allocate 0 bytes after warm-up. ## Related - [Why EasyEcs is fast](https://ecs.xgamedev.net/en/docs/why-fast): The storage, generated jobs and caches behind these numbers. - [Comparison with other ECS libraries](https://ecs.xgamedev.net/en/docs/comparison): The same work in Friflo.Engine.ECS, Arch and DefaultEcs, with every result. - [Queries and filters](https://ecs.xgamedev.net/en/docs/guide/queries): `Query`, struct jobs, `Count` and `Any`, and what a job declares. - [Systems and [ForEach]](https://ecs.xgamedev.net/en/docs/guide/systems): Batch methods, parallel methods, groups, intervals and timings. --- # Why EasyEcs is fast > The mechanisms behind EasyEcs' speed, each tied to a benchmark: aligned archetype columns, 16-byte entity records, presence bits, generated jobs and SIMD. URL: https://ecs.xgamedev.net/en/docs/why-fast Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/why-fast.md EasyEcs is fast because a server tick does the least work the data allows: it walks dense, aligned columns, skips 64 rows with one bit test, calls your code without a delegate, changes structure without a command buffer and allocates nothing. None of this needs you to write unusual code: a plain `[ForEach]` method gets all of it. Each section below names one mechanism, where it lives in the source and the benchmark that measures it. - A [ForEach] write, per entity: **0.91 ns**, two plain arrays take 1.28 ns - [Changed] over a full scan: **73×**, 10 of 100,000 rows written since the last run - Allocated per server tick: **0 B**, 100,000 entities, after warm-up ## The short answer | Mechanism | What it saves | Measured | | ------------------------------------------------------------------------------------------------------- | ---------------------------------------- | ---------------------------------------------------- | | [Archetype tables, 64-byte-aligned columns](https://ecs.xgamedev.net/en/docs/why-fast#archetype-tables) | Pointer chasing and split cache lines | 0.91 ns per entity, below two plain arrays (1.28 ns) | | [16-byte entity records](https://ecs.xgamedev.net/en/docs/why-fast#entity-records) | A second lookup per handle access | `MicroBenchmarks.HandleAccess` | | [Presence bits](https://ecs.xgamedev.net/en/docs/why-fast#presence-bits) | A row copy per state change | 517 μs against 1.00 ms for Friflo, which moves rows | | [Generated struct jobs](https://ecs.xgamedev.net/en/docs/why-fast#generated-jobs) | A delegate call per row | 33.7 μs against 145 μs for a `Query` loop | | [Lock-free query cache](https://ecs.xgamedev.net/en/docs/why-fast#query-cache) | Locks and table searches per call | 21.6 ns per query call | | [Change-tick summaries](https://ecs.xgamedev.net/en/docs/why-fast#change-ticks) | Visiting rows nobody wrote | 525 ns against 38.6 μs for a scan | | [Immediate structural changes](https://ecs.xgamedev.net/en/docs/why-fast#structural-changes) | Recording and replaying a command buffer | `StructuralChangeComparison` | | [Zero allocation](https://ecs.xgamedev.net/en/docs/why-fast#zero-allocation) | GC pauses | 0 B per tick | | [SIMD](https://ecs.xgamedev.net/en/docs/why-fast#simd) | One instruction per row or per word | 1.20 μs to count 100,000 rows bit by bit | | [The parallel runner](https://ecs.xgamedev.net/en/docs/why-fast#parallel-runner) | Waking threads that do not pay | 884 μs against 1.68 ms | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Archetype tables with aligned columns Entities with the same set of components share a table (an archetype): one column per component type, one row per entity, structure of arrays. A system walks the columns it needs front to back, which is the access pattern hardware prefetchers and vector units handle best. ```mermaid flowchart LR M["Meta[id]
16 B per entity"] -->|table + row| T subgraph T["Table {Position, Velocity, Burning}"] S["Slots: EntityId per row (8 B)"] P["Position column
64-byte aligned"] V["Velocity column
64-byte aligned"] B["Burning column
+ presence bits"] end ``` - **Unmanaged columns are pinned and aligned.** A column of a type without references is a byte array on the pinned object heap whose row 0 starts on the first 64-byte boundary (`Archetype.Aligned`). A row of a power-of-two-sized component never straddles two cache lines, vector loads stay aligned, and the GC never scans or moves the column. - **Columns are contiguous**, not pages: a handle access is one indexed load. Paging would only save the copy when a table grows, which `InitialEntityCapacity` removes ([D7](https://ecs.xgamedev.net/en/docs/decisions)). - **Each row's entity is one 8-byte `EntityId`** (version and index side by side), so a handle is built with one load. - **Moves follow cached edges.** Gaining a component the table has no column for copies the row to the target table along a transition cached per component bit (and per generic signature for several components), with a copy plan computed once per edge. The aligned columns are why the generated job beats the same loop over two plain arrays: **Add Velocity to Position for 10,000 entities** | Case | Mean | vs baseline | Allocated | | ------------------ | ------- | ----------- | --------- | | RawArrayWrite | 12.8 μs | 1.01× | 0 B | | ForEachSystemWrite | 9.13 μs | 0.72× | 0 B | | ForEachWrite | 9.55 μs | 0.75× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## 16-byte entity records Everything the world keeps per entity id is one `EntityMeta`: its table, its version and its row, 16 bytes, so four fit in a 64-byte cache line (`EntityMeta.cs`). The component set is the table's mask, not a per-entity copy. `entity.Get()` is a version check on that record, a column lookup in the table (bit to column, one small array whose 16-byte entries hold the column and its presence bits) and one indexed load. - Ids are recycled last in, first out: a freed id's cache lines are still warm when it comes back, and the records stay bounded by the peak number of live entities. - The records never shrink, which lets handles index them without bounds checks. | Case | Mean | vs baseline | Allocated | | ------------------ | ------- | ----------- | --------- | | HandleAccess | 3.33 μs | 0.26× | 0 B | | TryGetEntity | 3.60 μs | 0.28× | 0 B | | TrackedHandleWrite | 8.37 μs | 0.66× | 0 B | | SingletonAccess | 1.01 μs | 0.08× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Each row repeats its call 1,000 times. ## Presence bits Removing a component does not move the entity. The row keeps its place and clears one bit in the column's presence bits (64 rows per `ulong`); adding the component back sets the bit again ([D6](https://ecs.xgamedev.net/en/docs/decisions)). Only gaining a component the table has no column for moves the row, so a state that comes and goes (stunned, burning, dead) costs a bit flip after the first time. ```mermaid flowchart LR A["Remove<Stunned>()"] --> B["clear the row's bit"] B --> C["the entity keeps its row"] D["Set(new Stunned())"] --> E{"table has a
Stunned column?"} E -->|yes| F["set the row's bit"] E -->|no, first time| G["copy the row to
the table with one"] ``` Queries read the bits too. Each column counts its rows lacking the component, so per table a pass knows whether to skip it, walk every row with no test, or test bits, 64 rows per load. A rare state in a large table costs a pass over the words where it is set: **10 burning units among 100,000 in one table** | Case | Mean | vs baseline | Allocated | | --------------- | ------- | ----------- | --------- | | PassOverTheFew | 386 ns | — | 0 B | | QueryTheFew | 365 ns | — | 0 B | | CountTheFew | 13.6 ns | — | 0 B | | PassOverTheRest | 52.3 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Archetype libraries without presence bits move the entity to another table and back: **Stun 5% of 100,000 fighters, then recover them** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------ | ------- | ---------- | --------- | | EasyEcs | Toggle | 517 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Toggle | 1.00 ms | 1.94× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Generated struct jobs instead of delegates A `[ForEach]` method is compiled into a struct job by the source generator, and the world runs it through a generic method constrained to that struct: `world.ForEach(ref job, in filter)`. The JIT specializes the row loop for each job type and inlines your method into it. There is no delegate, no virtual call per row and no closure. ```mermaid flowchart LR U["[ForEach] static void Move(ref Position p, in Velocity v)"] --> G["generator"] G --> J["struct MoveJob : IForEach<Position, Velocity>
+ INoStructuralChanges"] G --> F["static readonly QueryFilter"] G --> A["access: writes Position, reads Velocity"] J --> L["world.ForEach<Position, Velocity, MoveJob>
specialized and inlined by the JIT"] ``` What the generator also decides for you: - **`INoStructuralChanges`** when the method is static, takes no `World` and uses its `Entity` only to read: the pass then skips the bookkeeping that keeps structural changes safe. A method that does change structure gets the safe loop. - **`Writes`**, from the `ref` parameters, so a structural change mid-pass carries exactly those writes to the entity's new row, and tracked components count as written only through `ref`. - **The system's access** (reads and writes per component and singleton), which decides which systems may share a [parallel stage](https://ecs.xgamedev.net/en/docs/why-fast#parallel-runner). - **The filter** as a `static readonly` field, built once. The generated code reaches private methods through `UnsafeAccessor`, so systems need no `partial` and the call compiles to a direct call. A static `[ForEach]` method outside a system gets an entry point that takes the world: it runs as fast as the struct job it replaces, written by hand. **Count the wounded of 100,000 fighters outside a system** | Case | Mean | vs baseline | Allocated | | -------------- | ------- | ----------- | --------- | | Runner | 33.7 μs | 1.00× | 0 B | | HandWrittenJob | 56.7 μs | 1.69× | 0 B | | Query | 145 μs | 4.3× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Lock-free query cache snapshots A query call does not search tables. The world keeps a cache keyed by the query's components and filter sets (required, excluded, any, changed, removed); each entry is an immutable snapshot of the matching tables and one row filter per table. When a new table appears, every matching entry is replaced copy-on-write and published with `Volatile.Write`, so readers never lock and never see a list being changed. In front of the cache, each call signature keeps a small memo of its first four filters, and a `QueryFilter` holds no object reference, so building one is a plain struct copy ([D18](https://ecs.xgamedev.net/en/docs/decisions)). ```mermaid flowchart LR C["world.Count<Npc>(filter)"] --> M{"memo of this
signature"} M -->|hit| E["entry: tables + row filters"] M -->|miss| D["cache dictionary"] --> E N["new table"] -->|copy-on-write,
Volatile.Write| E ``` **The cost of a query call: counting a few entities** | Case | Mean | vs baseline | Allocated | | ------------ | ------- | ----------- | --------- | | FilterAtCall | 74.8 ns | 1.00× | 0 B | | FilterOnce | 21.6 ns | 0.29× | 0 B | | NoFilter | 42.9 ns | 0.57× | 0 B | | PastTheMemo | 88.0 ns | 1.18× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Change-tick summaries per word and per block A component marked `ITrackChanges` gets a hidden column of 8-byte ticks: each row's tick of its last write. On top of it the table keeps summaries ([D23](https://ecs.xgamedev.net/en/docs/decisions)): ```mermaid flowchart TB T["column: latest tick"] -->|older than the pass| S1["skip the table"] T --> B["block of 4,096 rows:
latest tick + written words"] B -->|older| S2["skip the block"] B --> W["word of 64 rows: 32-byte summary
latest tick, its rows, bound of the rest"] W -->|rest older| R["take the written rows from the summary"] W -->|mixed| C["compare the row ticks, 4 per SIMD instruction"] ``` A `[Changed]` pass skips a table nobody wrote with one load, then unwritten blocks, then unwritten words (four summaries per SIMD compare), and finds the next written word of a block with one bit scan. Removing a tracked component stamps the row's tick while the row clears its presence bit, so `[Removed]` needs no extra storage, and its own block summaries keep writes of `T` from making it visit their words. Components without `ITrackChanges` have no column and no stamping code: the checks are JIT-time constants. **Replicate the 10 of 100,000 entities written since the last run** | Case | Changed | Mean | vs baseline | Allocated | | --------- | ------- | ------- | ----------- | --------- | | Tick | False | 38.6 μs | — | 0 B | | QueryTick | False | 476 μs | — | 0 B | | Tick | True | 525 ns | — | 0 B | | QueryTick | True | 720 ns | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Immediate structural changes Adding, removing, creating and destroying apply at once, also in the middle of a pass over the same table ([D2](https://ecs.xgamedev.net/en/docs/decisions)). Other libraries record such changes in a command buffer and replay them later, which costs a record per change and a second walk. EasyEcs pays only inside passes: - While a pass runs, a row that loses its entity becomes a tombstone (a negative id) instead of being filled, so rows never shift under the pass. The last pass to end closes the tombstones with vectorized scans. - A pass records each table's row count before it walks, so entities created or moved in during the pass are not visited: each entity is visited at most once. - Every change that can reallocate storage, move rows or flip presence bits bumps `StorageVersion`. The row loop checks it after each entity and re-reads its column refs only when it changed. Tables without tombstones run a row loop compiled without the tombstone check ([D25](https://ecs.xgamedev.net/en/docs/decisions)). **10 killed** **Mark the dead and revive them during two passes over 100,000 units** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | --------------- | ------- | ---------- | --------- | | EasyEcs | Direct | 78.2 μs | 1.00× | 0 B | | Friflo.Engine.ECS | CommandBuffer | 75.4 μs | 0.96× | 0 B | | Arch | CommandBuffer | 184 μs | 2.36× | 5.30 KB | | DefaultEcs | CommandRecorder | 496 μs | 6.3× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **1,000 killed** **Mark the dead and revive them during two passes over 100,000 units** | 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 | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## Zero allocation A busy world allocates nothing per tick, so a long-running server has no GC pauses from the ECS. The rule is enforced, not hoped for: `AllocationTests` run a frame of updates, queries, structural changes, tracked removals, index churn, prefab waves, relations, cascades and parallel passes 100 times after warm-up and require `GC.GetAllocatedBytesForCurrentThread()` to be unchanged, on every `dotnet test`. What makes it hold: - **Struct jobs and struct enumerators**: no delegate, no closure, no boxing on any iteration path. - **Pooled cold state**: a `Query` walk's per-table bookkeeping lives in a `QueryWalk` pooled per thread and nesting level. - **Caches built once**: transition edges, query entries, prefab target tables and overflow masks are allocated when first needed, never on the steady path. - **Bounded growth**: tables double when full and never shrink, ids are recycled, buffers are reused. - **The parallel runner** uses reusable thread-pool work items, not `Parallel.For` (a closure and state per call). The same tick in other libraries, with what each allocates per tick: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. `AllocationTests` once caught a lambda that captured locals in `World.Update`: the closure was allocated at method entry even when its branch was not taken. That is the kind of regression the test exists for. ## SIMD Vector instructions appear where they measure ([D21](https://ecs.xgamedev.net/en/docs/decisions)): | Where | What is vectorized | | --------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | Table matching | Component masks are 256-bit `Vector256` bitsets: one test per table for the first 256 component types | | `Count` / `Any` on tables whose rows must be tested | The set bits of the row words, 8 words per step with AVX-512 (`Vector512`), else `Vector` | | Change filters | Word summaries 4 per compare; row ticks of mixed words 4 per instruction | | Writes of a run of rows | One vectorized fill of their ticks | | Closing tombstones | Rows read as `long`s and searched for negative ids | | Your systems | Batch `[ForEach]` methods take spans of aligned columns, ready for `Vector` | | Case | Mean | vs baseline | Allocated | | ----- | ------- | ----------- | --------- | | Count | 1.20 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Movement over 100,000 entities: per entity and as a vectorized batch method** | Library | Case | Mean | vs EasyEcs | Allocated | | ----------------- | ------------ | ------- | ---------- | --------- | | EasyEcs | Iterate2 | 253 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2 | 257 μs | 1.02× | 0 B | | EasyEcs | Iterate2Simd | 69.5 μs | 1.00× | 0 B | | Friflo.Engine.ECS | Iterate2Simd | 80.7 μs | 1.16× | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## The parallel runner Parallel work runs on the calling thread plus up to `MaxDegreeOfParallelism - 1` reusable `IThreadPoolWorkItem` helpers ([D22](https://ecs.xgamedev.net/en/docs/decisions)). Two kinds of work use it: - **Parallel stages**: with `WorldOptions.ParallelSystems`, consecutive systems with no order between them and no conflicting access (from the generated access sets) form one stage and run at once. - **`[ForEach(Parallel = true)]`**: a method's rows run in chunks, a multiple of 64 rows (so presence-bit words never straddle chunks), about four per thread, between 1,024 and 16,384 rows. ```mermaid flowchart LR U["Update"] --> S{"helpers paid off
last runs?"} S -->|yes| P["caller + pool work items
take chunks"] S -->|no| A["caller runs alone"] A -->|probe after 16..1,024 runs,
or when 1.5x slower| P P -->|a fifth faster than the work| S ``` Each job and each stage measures its own runs: helpers stay while they make a run at least a fifth faster than its work, and a job that runs alone probes again after a period that doubles from 16 to 1,024 runs. Waking a parked pool thread costs from a few to a few hundred microseconds, so a small pass between ticks runs alone instead of burning CPU. There is no spinning and no dedicated thread. **Steering 100,000 entities, one thread and parallel** | Case | Parallel | Mean | vs baseline | Allocated | | --------- | -------- | ------- | ----------- | --------- | | Tick | False | 1.68 ms | — | 0 B | | EntityJob | False | 1.92 ms | — | 0 B | | Tick | True | 884 μs | — | 0 B | | EntityJob | True | 896 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. **Four independent systems, sequential and as one parallel stage** | Case | Parallel | Mean | vs baseline | Allocated | | ---- | -------- | ------ | ----------- | --------- | | Tick | False | 420 μs | — | 0 B | | Tick | True | 295 μs | — | 0 B | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. The reference machine has 4 cores, and the parallel rows of this run carry a large error: read them as "faster on several cores", not as a precise speed-up. ## What it costs The same choices have prices, and they are deliberate: - **Gaining a new component copies the row** to another table. The first time a state appears on an entity it moves; after that it flips a bit. - **Tables never shrink.** Memory is bounded by the peak number of entities each table held. - **One owner thread per world.** Structural changes and component writes belong to it ([D13](https://ecs.xgamedev.net/en/docs/decisions)); parallelism comes from parallel stages, parallel methods and one world per thread. - **.NET 10 only** ([D15](https://ecs.xgamedev.net/en/docs/decisions)): no Unity, no older runtimes. ## Related - [Performance guide](https://ecs.xgamedev.net/en/docs/performance): Which API to pick, the rewrites that pay and every benchmark. - [Architecture](https://ecs.xgamedev.net/en/docs/architecture): Storage, transitions, the query cache and passes in detail. - [Design decisions](https://ecs.xgamedev.net/en/docs/decisions): Why each choice was made, what was weighed and the numbers. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): The same work in Friflo.Engine.ECS, Arch and DefaultEcs. --- # Architecture > How EasyEcs stores entities and components, keeps tables dense under churn, caches queries, schedules systems and generates code, and what must always hold. URL: https://ecs.xgamedev.net/en/docs/architecture Version: EasyEcs 4.6 Last updated: 2026-10-19 中文版: https://ecs.xgamedev.net/zh/docs/architecture.md How EasyEcs stores data, walks it and schedules the code that changes it, and why. You do not need this page to use the library ([Getting started](https://ecs.xgamedev.net/en/docs/getting-started) is the place for that); it is for contributors and for anyone who wants to know what a call costs before making it. Every change to EasyEcs must keep four guarantees: - **No allocation on hot paths**: queries, iteration, component access and structural changes after warm-up. - **Bounded memory under churn**: ids, rows and buffers are recycled, so memory follows the peak population. - **Cache-friendly layouts**: 64-byte lines, columns that SIMD can walk front to back. - **Immediate structural changes**: adding, removing, creating and destroying take effect at once, also while a pass iterates. ## Storage model ```mermaid flowchart TB subgraph W["World (one owner thread)"] Meta["Meta[id]: EntityMeta, 16 B
table · version · row"] T["Table (archetype)
Slots[row]: EntityId · one column per component
presence bits · change ticks · add edges"] QC["Query cache
filter → tables + row filters"] S["Singletons[slot]"] Sys["Schedules: one per system group,
split into stages"] Idx["Value and relation indexes
(only when created)"] end Meta -->|table + row| T QC --> T Idx -->|entity ids| Meta ``` - **Per entity**, the world keeps one `EntityMeta`: its table, version and row, 16 bytes, so four share a 64-byte line. The component set is the table's mask and is not stored per entity. The only other per-entity state is opt-in: a value index, once a world creates one, keeps a node per entity id. - **Tables are structures of arrays.** An archetype is a table with one column per component type and one row per entity, plus an `EntityId` per row (index and version side by side, 8 bytes, so a handle needs one load). Passes walk columns front to back, which hardware prefetchers and SIMD handle best. - Unmanaged columns are pinned arrays (pinned object heap) whose row 0 starts on a 64-byte boundary: a row of a power-of-two-sized component never straddles two lines, and vector loads stay aligned. - Columns of types that hold references are plain `T[]`; a row's references are cleared when the row loses its entity or its component, so the GC can collect what they pointed to. - A [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers) column holds one reference per row to that row's own list, created by its first write. Moving the row moves the reference; snapshots and clones copy the elements into new lists. - Tables double when full and never shrink: each is bounded by the most entities it ever held. - **Presence bits.** Removing a component keeps the entity in its table and clears the row's bit for that component (one bit per row, 64 rows per `ulong`). A column gets its bits on its first removal; until then every row has the component and the column carries no bits. Each column also counts its living rows that lack the component, so a pass knows per table whether it can skip it, walk every row, or test bits. `Count` and `Any` answer a table from those counts when only one column varies, without reading bits. - **Disabled components** are presence bits too: `entity.Disable()` clears `T`'s bit and adds a `Disabled` tag, whose column the table gains on the first disable (one row move per table, then bit flips). - **Groups.** `world.GroupBy()` keys tables by the value of an [`IGroup`](https://ecs.xgamedev.net/en/docs/guide/groups) component as well as by their mask, so the entities of one group are contiguous and `QueryFilter.InGroup(g)` walks only their tables. - **Masks** (`BitMask`) are 256-bit SIMD bitsets with an overflow. Component bits are `ushort`s, so a process can use up to 65,536 component types: the first 256 are inline (one `Vector256` test per table match), the rest go to an overflow array that is allocated when a table or a transition is first built, never on a hot path. `QueryFilter` keeps its bits past 255 as an interned id, so a filter holds no object reference ([D18](https://ecs.xgamedev.net/en/docs/decisions#d18-no-interceptors-for-query-calls-filters-carry-no-references)). ### Change ticks A component marked `ITrackChanges` brings a hidden column of 8-byte ticks into every table that has it: the world's change tick of each row's last write. Writes stamp it (a run of rows with one vectorized fill) and keep summaries at three levels, so a pass can skip what nobody wrote: | Level | Summary | Lets a `Changed` pass | | ------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | Column | the latest tick of any row | skip a table nobody wrote since its tick, with one load | | Block of 4,096 rows | the words at the block's latest tick (a bit mask) and a bound for the others | find the next written word with one bit scan | | Word of 64 rows | 32 bytes: latest tick, the rows holding it, a bound for the other rows, a bound for removals | take a word's written rows from its summary, without reading their ticks | Only words that mix older and newer ticks compare their rows, four per SIMD instruction. The result is 64 bits per word, like presence bits, so it rides on the same row filters. Removing a tracked component stamps its row's tick and clears its presence bit: a `Removed` filter is "bit clear and tick recent enough", so removal detection needs no extra storage, and removals keep their own block summaries so that writes do not make removal passes visit their words ([D23](https://ecs.xgamedev.net/en/docs/decisions#d23-change-summaries-per-block-removals-summarized-apart)). Untracked components have no tick column and no stamping code: the checks are JIT-time constants. ### Value and relation indexes `world.Index()` keeps, per key, the key's entities in one id array (`IndexHead`); a leaving entity's hole is filled by the key's next entity, so entities never move under a loop ([D24](https://ecs.xgamedev.net/en/docs/decisions#d24-an-indexs-key-holds-its-entities-in-one-array)). Keys that are entities of the world (relations, `ChildOf`) sit in an array indexed by the target's id, so a relation lookup hashes nothing. The index is kept on write: `Set`, `CreateEntity` and `CreateEntities` call one inlined hook that the JIT removes for components without an index. A write through a `ref` cannot be seen (the ref is handed out before the value changes), so the analyzer rejects it ([EECS015](https://ecs.xgamedev.net/en/docs/guide/analyzer)) instead of every lookup paying for it. The first lookup builds the index with one query; destroying an entity or removing an indexed component unlinks it at once. ### Why rows move only on adds A table copies an entity's row when the entity gains a component its table has no column for: that is what keeps iteration dense. States that come and go (stunned, burning, dead) flip presence bits after their first time, so they copy nothing ([D6](https://ecs.xgamedev.net/en/docs/decisions#d6-removing-a-component-keeps-the-row)). Columns are contiguous arrays, not pages: paged columns iterate at the same speed but add an indirection to every handle access, and save only the copy when a table grows, which `InitialEntityCapacity` and `EnsureCapacity` remove ([D7](https://ecs.xgamedev.net/en/docs/decisions#d7-contiguous-columns-not-pages)). ## Memory layout at a glance ```mermaid flowchart LR M["Meta[id]
EntityMeta 16 B
4 per cache line"] subgraph A1["Table {Position, Velocity, Stunned}"] I1["Slots[]: EntityId"] P1["Position[] (64-byte aligned)"] V1["Velocity[] (64-byte aligned)"] S1["Stunned[] + presence bits"] end subgraph A2["Table {Position, Health}"] I2["Slots[]: EntityId"] P2["Position[]"] H2["Health[] + change ticks"] end M -->|table + row| A1 M -->|table + row| A2 ``` - `entity.Get()` is a version check on the 16-byte record, a column lookup in the table (bit to column, a small array), one presence-bit test when the column has bits, then an indexed load. - `CreateEntity(a, b, …)`, `Set(a, b, …)` and `GetOrAdd()` follow transitions cached per table, so a repeated structural change is one array load plus the row copy. ## Entity lifecycle ```mermaid stateDiagram-v2 [*] --> Free Free --> Alive: CreateEntity / Instantiate / Clone Alive --> Alive: Set a new component (row copied to another table) Alive --> Alive: Remove, Disable, re-add (presence bit, no move) Alive --> Destroyed: Destroy while it holds a cleanup component Destroyed --> Free: last cleanup component removed Alive --> Free: Destroy (version + 1, row removed, id recycled) ``` - `Entity` is a handle: world, id and version. Every operation validates the version, so a handle to a destroyed entity never touches the entity that reuses its index. Store `EntityId`s in components, not handles. - Ids are recycled last in, first out: recently freed ids still have warm cache lines, and `Meta` stays bounded by the peak number of live entities. `Meta` never shrinks (on `Dispose` it is cleared), which lets handles index it without bounds checks. - An entity destroyed while it holds an [`ICleanupComponent`](https://ecs.xgamedev.net/en/docs/guide/cleanup-and-disable) loses its other components and keeps a `Destroyed` tag until a system removes its last cleanup component. ## Archetype transitions and row removal - An entity moves only when it gains a component its table has no column for. The move copies the components both tables have (a copy plan of column pairs, computed once per edge) into a new row of the target table: unmanaged values as bytes, managed ones through their typed copy. - Single-component adds follow **edges** cached on the table per component bit. Multi-component adds follow **set edges** keyed by the dense index of the call's generic signature (`(T1, …, Tn)`). The first call per table and signature builds the target mask and does one hash lookup; later calls are one array load. - `CreateEntity(in T1 … in Tn)` places the entity in its final table directly. - **Prefabs and clones.** A `Prefab` is one row of a private world, so no query of yours sees it. `Instantiate` finds the target table from the prefab table's mask once and caches it; `Clone` uses the original's table. Then one row copy fills the new entity: unmanaged bytes, managed values through their clone (a `DynamicBuffer` gets a new list with the same elements), presence bits for what the source lacks, and the current tick for each tracked component it has. `Instantiate(prefab, span)` reserves ids and rows once for the whole wave. - A row that loses its entity is filled at once by the table's last row when no pass is iterating, so tables stay dense. While a pass iterates, the row becomes a **tombstone** (index -1) instead, so rows never shift under the pass; the last pass to end closes the tombstones, found with vectorized scans of the rows read as `long`s. ## Query cache ```mermaid flowchart LR Call["Query / Count / [ForEach]"] --> Memo{"Memo of the call's
signature (4 ways)"} Memo -->|hit| Entry["Cache entry
tables + row filters"] Memo -->|miss| Dict["ConcurrentDictionary
keyed by the filter"] Dict -->|first use: scan every table| Entry New["New table created"] -->|copy-on-write| Entry ``` A query's key is its component sets: required, excluded, `WithAny`, `Changed`, `Removed` and the group. Its entry holds an immutable snapshot: the tables whose mask has every required component and the column of every `Removed` component (and, with `WithAny`, at least one of those), each with a row filter naming the columns whose presence bits and ticks the pass tests. An excluded component does not rule a table out, since its rows may lack it; the row filter does. Each call signature keeps a memo of its first four filters, so a hot call usually finds its entry without hashing; past the memo, the dictionary's alternate lookup probes with the call's own bits. When a new table is created, under the structural gate, every matching entry is replaced copy-on-write and published with `Volatile.Write`: readers never lock and never see a list being changed. The first use of a query shape costs one scan of every table; a new table costs a pass over the cached shapes. Both are cold paths. Per pass and table, the row filter picks one of three modes from the column counts: skip the table, walk every row, or test bits. A `Changed` or `Removed` filter always tests: its words also AND in the rows whose tick reaches the pass's tick, which travels with the pass while the plan is shared. ## Iteration and structural changes Every iteration API walks tables front to back. What differs is the bookkeeping a pass needs: - **Jobs that make no structural change** (`INoStructuralChanges`, which the generator adds to a static `[ForEach]` method that takes no `World` and only reads through its `Entity` parameter) walk dense tables with no per-row check and tables with presence bits 64 rows per word. Their passes freeze the world's structure: a structural change inside throws. Batch methods (spans) and `ForEachBatch` receive whole runs of consecutive passing rows. - **Other passes** register with the world (`BeginPass` / `EndPass`), so removed rows become tombstones instead of being filled. A pass records each matching table's row count before walking it; rows appended during the pass (entities created or moved into a matching table) are past that count and not visited. Each entity is visited at most once, and one that loses a queried component or is destroyed before its turn is skipped. - Each table is walked by a row loop compiled twice: for a table with tombstones (each row tests its id) and for one without (no test) ([D25](https://ecs.xgamedev.net/en/docs/decisions#d25-structural-row-loops-are-compiled-for-tables-without-tombstones)). After each entity, the pass compares the world's `StorageVersion` with the value it last saw: every change that can reallocate storage, move rows or flip presence bits bumps it, and the pass then re-reads its column refs and bits from the next row. - When a job changes the archetype of the entity it visits, its writes through the refs land in the old row (now a tombstone). After the job returns, the pass copies the components the job writes (`Writes`, generated from its `ref` parameters) to the entity's new row, so no write is lost. - `Query` follows the same rules. Its enumerator keeps the hot state (row, row count, entity rows, column refs) in its own fields, and every member a loop calls is inlined, so the JIT keeps them in registers. The cold state lives in a `QueryWalk`, pooled per thread, reached once per table and per structural change. A ticket tells a walk's current use from a copy of an enumerator that already ended. The rules from the user's side: [Structural changes during iteration](https://ecs.xgamedev.net/en/docs/guide/structural-changes). ## Systems ```mermaid flowchart LR Add["AddSystem"] --> Sort["Order: registration order,
moved by UpdateBefore / UpdateAfter"] Sort --> Stages["Stages: after the latest system
it follows or conflicts with"] Stages --> Run["Update(): stage by stage,
OnUpdate + generated [ForEach]"] Run --> Tick["ChangeTick + 1 per stage"] ``` - Each system group has one schedule: its systems in registration order, moved as `[UpdateBefore]` / `[UpdateAfter]` require (a stable topological sort; a cycle throws in `AddSystem` before anything changes). The schedule is split into stages: a system goes to the stage after the latest one holding a system it must follow, by an ordering or by an earlier conflicting access (`SystemAccess`). Of two conflicting systems the earlier one always finishes first. Both arrays are copy-on-write; rebuilding them is O(systems²), once per `AddSystem` or `RemoveSystem`. - `Update()` and `Update()` are synchronous. For each due, enabled system they call `OnUpdate()` and the generated `[ForEach]` methods. Each stage advances the change tick once, and each update once more. - `AddSystem` calls `OnCreate()`; `RemoveSystem` and `Dispose` call `OnDestroy()`, `Dispose` in reverse order. - An exception propagates out of the update, or, with `SystemErrorPolicy.Disable`, switches its system off and stays in `system.Error`. - Systems cooperate through data only ([D1](https://ecs.xgamedev.net/en/docs/decisions#d1-state-changes-are-data-no-events-or-callbacks)), so all behavior runs in schedule order. User-facing details: [Systems](https://ecs.xgamedev.net/en/docs/guide/systems). ## Source generators and analyzer | Part | What it does | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ArityGenerator` | Writes every T1..T9 family of `EasyEcs.Core` from one template each (`Entity.Set` / `Remove`, `World.CreateEntity` / `CreateEntities` / `DestroyEntities`, the job interfaces, `ForEach` and its variants, `Query`, `Count`, `Any`). Runs only for `EasyEcs.Core`. | | `SystemGenerator` | Turns `[ForEach]` methods into struct jobs (per entity, or per run of rows for span parameters) in a file class of their own, which call the user's method through `[UnsafeAccessor]` ([D16](https://ecs.xgamedev.net/en/docs/decisions#d16-no-partial-generated-code-lives-outside-the-users-type)). Each system gets a `SystemCode` (its update and access set) registered by a module initializer; a static method outside a system gets an entry point. `[Changed]` / `[Removed]` become `Since(LastRunTick + 1)` and a declared read of `T`; `Parallel = true` runs the job over chunks. Jobs that cannot change structure get `INoStructuralChanges`. | | `ComponentGenerator` | C# 14 extension members per component and singleton: `entity.Health`, `HasHealth`, `SetHealth(…)`, `IsDead`, `world.Clock`, `world.KillsIndex`, `item.Position` per query shape, the buffer and prefab writers, and the registration of the types a save may name. | | `EasyEcsAnalyzer` | Reports EECS002–EECS034: input the generators skip, and code that breaks the [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles). Generators never report diagnostics; both use the same checks. [EasyEcs.CodeFixes](https://ecs.xgamedev.net/en/docs/guide/analyzer) offers the mechanical fixes. | The generators follow the incremental rules: `ForAttributeWithMetadataName` or syntax-only predicates first, models that are equatable records of strings (no symbol, node or location survives a transform), a tracking name per stage, and a test (`GeneratorTests`) that an unrelated edit leaves the stages cached. ## Type indices `TypeIndex` gives each type a dense, process-wide index within a family on first use. It is a static readonly field, so the JIT folds it to a constant: - `ComponentType.Bit`: the mask bit. Assigning it registers the type's column operations (size, managed or not, create, grow, copy, clone, clear), which tables use without knowing `T`. A tracked component also registers its hidden tick column, paired with its own, so every copy, move and growth carries the ticks. - `SingletonType.Index`: the singleton slot. `SystemGroup.Index`: the system group (0 is the default group). - `ComponentSignature`: one index per generic signature of a multi-component call, keying set edges and query memos. Every world uses the same indices, so masks are comparable across worlds. When a collectible assembly unloads, its component bits are reused once no live world mentions them ([D17](https://ecs.xgamedev.net/en/docs/decisions#d17-unloading-removes-types-from-worlds-bits-are-reused)). ## Threading ```mermaid flowchart TB Owner["Owner thread
Update, queries, structural changes"] --> Gate{"Structural gate
plain flag"} Owner --> Stage["Parallel stage or
parallel [ForEach]"] Stage -->|freezes| Gate Stage --> Helpers["Caller + thread-pool helpers
claim items by one cursor"] Helpers --> Shared{"Shared gate (CAS)
cold paths only"} ``` - Structural changes, system changes, `Capture` and `Restore` enter the world's **structural gate**, which belongs to the owner thread: a plain flag, checked and set on the way in, cleared on the way out, with no atomic instruction. A parallel stage of systems, the chunks of a parallel `[ForEach]` and a batch job freeze it while they run, so a structural change inside them throws `InvalidOperationException`, deterministically, as does one reentered under the gate. - The cold paths that the threads of a parallel stage reach on their own (the first match of a query shape, a singleton resolved first, closing tombstones when the last pass ends) take a separate **shared gate**, a compare-and-swap flag with a spinning wait. Both flags sit on a cache line of their own. - Queries, `Get` and `Has` are lock-free; component values are unsynchronized by design. The model is **one world per owner thread** ([D13](https://ecs.xgamedev.net/en/docs/decisions#d13-one-owner-thread-per-world)). The analyzer reports structural changes in `[ForEach]` methods that promise none (EECS013) and in delegates handed to other threads (EECS014). - Parallel runs use the calling thread plus reusable `IThreadPoolWorkItem` helpers that claim items through one `Interlocked` cursor (the run's epoch in the high 32 bits, so a helper that starts late never touches the next run). Each job and stage measures its runs and wakes helpers only while they make a run at least a fifth faster ([D22](https://ecs.xgamedev.net/en/docs/decisions#d22-parallel-runs-use-the-thread-pool-and-wake-helpers-only-when-they-pay)). Nothing is allocated per update. The rules from the user's side: [Threading](https://ecs.xgamedev.net/en/docs/guide/threading). ## Related - [Design decisions](https://ecs.xgamedev.net/en/docs/decisions): Why each of these choices was made, what was weighed against it, and the numbers. - [Performance](https://ecs.xgamedev.net/en/docs/performance): What these structures mean for the API you pick. - [API and complexity](https://ecs.xgamedev.net/en/docs/api): The cost of every public call. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): The same storage questions answered by Friflo, Arch and DefaultEcs. --- # FAQ > Short answers about using EasyEcs in game servers, simulations and real-time .NET backends: allocations, threading, Unity, Native AOT, saves and comparisons. URL: https://ecs.xgamedev.net/en/docs/faq Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/faq.md ## Is EasyEcs only for game servers? No. EasyEcs is a C#/.NET 10 ECS library for workloads that repeatedly update many entities: game servers, simulations and other long-running real-time backends. A world holds plain component data; systems process matching entities on a tick. The library does not assume that an entity is a player or that a tick comes from a game. For example, a service can model moving vehicles, devices or workers as entities and run movement, status and expiry systems over them. The architectural fit matters more than the label. Use an ECS when the same operations run over many changing items and predictable hot-path costs matter. A conventional database-backed CRUD service with little shared per-item work usually has no need for an ECS. EasyEcs supplies the world, queries, systems and state management; you supply the transport and host. The [ASP.NET Core and Worker hosting guide](https://ecs.xgamedev.net/en/docs/guide/hosting) shows one way to connect HTTP requests to a world without touching it from request threads. ## Is EasyEcs production ready? EasyEcs is published on [NuGet](https://www.nuget.org/packages/EasyEcs) under the MIT license and built for long-running .NET servers. What backs it up, in the repository: - Hundreds of NUnit tests, one file per feature, including allocation tests with a budget of 0 bytes, generator and analyzer tests, and a battle server that runs every feature at once ([the example](https://ecs.xgamedev.net/en/docs/example)). - BenchmarkDotNet suites for every feature and against Friflo.Engine.ECS, Arch and DefaultEcs, each result checked in setup ([Performance](https://ecs.xgamedev.net/en/docs/performance)). - CI that builds, tests, runs every sample and example, compiles the C# snippets of these docs and checks the generated API reference. - An analyzer that rejects the design mistakes an ECS makes easy (EECS002 to EECS034), with code fixes. What to weigh: it targets `net10.0` only, the API changes between minor versions while it matures (4.0 to 4.1 renamed and removed a few members, and in 4.2 reading a singleton that was never added throws; the [migration guide](https://ecs.xgamedev.net/en/docs/migration) lists each change), and the [changelog](https://ecs.xgamedev.net/en/docs/changelog) shows what each release changed. ## Does EasyEcs allocate? Not on hot paths. Queries, iteration, component access, `[ForEach]` systems, parallel runs and structural changes allocate nothing once the world is warmed up (its tables, query cache and pools have reached their peak sizes). The headline server tick of 100,000 entities takes 1.72 ms and allocates 0 B. BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. What allocates, on purpose: creating a world, the first entity of a new component set (a new table), the first use of a query shape, a table or a `DynamicBuffer` growing past its capacity, and cold tools such as `Describe`. `InitialEntityCapacity`, `EnsureCapacity(count)`, `EnsureCapacity(prefab, count)` and `bag.EnsureCapacity(n)` move growth out of the tick. ## Is it thread-safe? The rules are explicit and short ([D13](https://ecs.xgamedev.net/en/docs/decisions#d13-one-owner-thread-per-world)): - **A world has one owner thread.** Its systems, queries and component reads and writes run there. On a server, run one world per thread (one per map, zone or match): worlds share nothing, so they scale across cores without locks. - **Structural changes belong to the owner thread.** Adding or removing components and creating or destroying entities check a plain owner flag: a change made inside a parallel stage, a parallel `[ForEach]` or a pass that promised none throws instead of tearing the tables. The analyzer reports the off-thread changes it can see ([EECS013, EECS014](https://ecs.xgamedev.net/en/docs/guide/analyzer)). - **The parallelism EasyEcs adds is checked.** `WorldOptions.ParallelSystems` runs systems together only when their generated access does not conflict, with the same result as running them one by one; a `[ForEach(Parallel = true)]` method must change no structure and write no singleton (EECS010). - **Input from other threads** (network, IO) goes into a queue of yours that one system drains on the owner thread. Never keep a `ref` across an `await`: keep the `Entity` and get the component again. More in [Threading](https://ecs.xgamedev.net/en/docs/guide/threading) and [`ref` and `await`](https://ecs.xgamedev.net/en/docs/guide/refs-and-await). ## How do I run EasyEcs in ASP.NET Core or a Worker Service? Give the world one owner: a `BackgroundService` that builds it, calls `world.Update()` on a `PeriodicTimer` and saves it when the host stops. Request handlers never touch the world: they write requests into a bounded `Channel` that a system drains each tick (with a `TaskCompletionSource` for the reply), and read an immutable status the world publishes. A request for one entity (an actor, a player) is handled on that entity, on the owner thread, with `entity.Run(ref job, filter)`: one lookup for all the components the job needs, and `false` when the entity is gone or does not match ([One entity: `entity.Run`](https://ecs.xgamedev.net/en/docs/guide/queries#run-on-one-entity)). No hosting package is needed; [Hosting in a .NET server](https://ecs.xgamedev.net/en/docs/guide/hosting) has the whole server. ## How do I test a system? Build a world in the test, add the system and the entities and singletons it needs, call `world.Update()` and assert on the components. Systems never call each other, so there is nothing to mock; share the server's setup method so the test runs the real order. A zero-allocation budget is one more test: count `GC.GetAllocatedBytesForCurrentThread()` around warm updates ([Testing systems](https://ecs.xgamedev.net/en/docs/guide/testing)). ## How should I structure an EasyEcs project? The way `dotnet new easyecs` lays it out: components in `Components/` (one file per thing they describe, plain data), one system per file in `Systems/` with one job each, and `Program.cs` as the host that builds the world, sets the singletons, adds the systems in one place and runs the loop. Groups give each cadence its own update, input from other threads goes through a mailbox (a queue in a singleton), and `--tests` adds one test file per system ([Structuring a real project](https://ecs.xgamedev.net/en/docs/guide/project-structure)). ## How do I debug an ECS world? Ask the world: `world.Describe()` lists the tables with their components, entities and bytes, `entity.Describe()` returns an entity's component values (the debugger shows them too when you expand an `Entity`), `system.Stats` times every system with `WorldOptions.MeasureSystems`, and `system.Error` keeps the exception of a system switched off by `SystemErrorPolicy.Disable`. Read them on the owner thread between updates ([Debugging and diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics)). ## Can I use EasyEcs with Unity or Godot? No. EasyEcs targets `net10.0` only: it relies on C# 14 extension members, `Vector256` / `Vector512`, columns on the pinned object heap and current JIT behavior ([D15](https://ecs.xgamedev.net/en/docs/decisions#d15-net-10-only)), which Unity's runtimes do not offer. Godot is not a tested or supported target either: EasyEcs is built for servers and has no engine integration. The usual setup is EasyEcs on a .NET 10 game server and the client engine's own tools on the client; [EasyEcs and Unity Entities](https://ecs.xgamedev.net/en/docs/vs-unity-entities) says how the two models differ. ## How does EasyEcs compare with Arch, Friflo.Engine.ECS and DefaultEcs? All four are C# ECS libraries; they differ in what they do for you and what it costs. EasyEcs generates the loops from `[ForEach]` methods, applies structural changes immediately (no command buffers), tracks changes and removals as data, and checks the ECS rules at compile time. In 37 head-to-head benchmarks (BenchmarkDotNet, each library doing the same work its own idiomatic way), EasyEcs is faster in 24, within the measurement error in 11 and slower in 2. Its biggest leads: | What is measured | EasyEcs | Next fastest | Its time vs EasyEcs | The others | | ------------------------------------------------------------------------------------------------------------------------------ | ------- | ------------------------------------- | ------------------- | ---------------------------------------------------------- | | [Save 10,000 entities and load them back](https://ecs.xgamedev.net/en/docs/comparison#saves) | 146 μs | DefaultEcs 4.33 ms, 4.37 MB allocated | 30× | Friflo.Engine.ECS 143×, 6.52 MB allocated | | [Add a component to 100,000 entities by query, then remove it](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 78.7 μs | Arch 1.21 ms | 15× | DefaultEcs 103×; Friflo.Engine.ECS 154×, 4.00 MB allocated | | [Spawn 10,000 entities beside 100,000, then destroy them](https://ecs.xgamedev.net/en/docs/comparison#bulk) | 138 μs | Friflo.Engine.ECS 380 μs | 2.75× | Arch 2.96×; DefaultEcs 9.7×, 313 KB allocated | | [Query 100,000 players by value: a rating range, zone sums](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 127 μs | Friflo.Engine.ECS 317 μs | 2.49× | — | | [Create 1,000 parent-child squads, destroy them in cascade](https://ecs.xgamedev.net/en/docs/comparison#hierarchy) | 452 μs | Friflo.Engine.ECS 1.06 ms | 2.35× | — | | [Count 100 inventories through an index (1 item traded)](https://ecs.xgamedev.net/en/docs/comparison#indexes-and-relations) | 425 ns | DefaultEcs 838 ns | 1.97× | Friflo.Engine.ECS 3.2× | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. On the full server tick the four are closer: **One server tick of 100,000 entities** | Library | Time | vs EasyEcs | Allocated | | --------------------- | ------- | ---------- | --------- | | EasyEcs 4.6 | 1.68 ms | 1.00× | 0 B | | Friflo.Engine.ECS 3.6 | 1.83 ms | 1.08× | 0 B | | Arch 2.1 | 5.76 ms | 3.4× | 535 KB | | DefaultEcs 0.17 | 6.24 ms | 3.7× | 60.9 KB | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. Every result, with where another library is faster and why: [Comparison](https://ecs.xgamedev.net/en/docs/comparison#feature-by-feature), and the pages [vs Arch](https://ecs.xgamedev.net/en/docs/vs-arch), [vs Friflo](https://ecs.xgamedev.net/en/docs/vs-friflo) and [vs DefaultEcs](https://ecs.xgamedev.net/en/docs/vs-defaultecs). ## How do I save a world? Three tools, for three needs: | Need | Call | Page | | ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | | Undo, rollback, prediction, replays in memory | `world.Capture()` / `world.Restore(snapshot)` | [Snapshots](https://ecs.xgamedev.net/en/docs/guide/snapshots) | | A whole world to disk, a database or another process | `world.Save(output)` / `world.Load(bytes)` | [Saves](https://ecs.xgamedev.net/en/docs/guide/saves) | | A group of entities (a player and what it owns) to another world or server | `SaveEntities` / `LoadEntities`, `MoveEntities` | [Migration and unloading](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload) | | The durable part of an actor, restored onto its entity without counting as a change | `SaveEntities(output, ids, set)` / `LoadEntitiesInto(bytes, entities, markWritten: false)` | [Records](https://ecs.xgamedev.net/en/docs/guide/migration-and-unload#records) | ```csharp using System.Buffers; var output = new ArrayBufferWriter(); world.Save(output); // entities with their ids, components, singletons world.Load(output.WrittenSpan); // EntityIds stored in components still point at the same entities ``` Saves are built in from 4.1 ([D9](https://ecs.xgamedev.net/en/docs/decisions#d9-saves-are-built-in-with-nino)): unmanaged components are written as their raw rows with a hash of their fields, so a changed struct is detected at load; managed components, singletons and the unmanaged components marked `[NinoType]` go through [Nino](https://github.com/JasonXuDeveloper/Nino). Types are recorded by their Nino type id, so a load skips a component the process no longer has. ## Can I hot-reload game logic? Yes. Load your systems and components from a plugin assembly in a collectible `AssemblyLoadContext`. To replace it, save the world, call `world.RemoveTypes(assembly)` (its systems, singletons, indexes and components leave the world; the entities stay), unload the context, load the new version and `Load` the save: types are saved by type id, so the new version's components take the values ([D17](https://ecs.xgamedev.net/en/docs/decisions#d17-unloading-removes-types-from-worlds-bits-are-reused)). The [HotReload sample](https://github.com/JasonXuDeveloper/EasyEcs/tree/master/samples/HotReload) does it end to end and checks that the old assembly was collected. ## Does EasyEcs work with Native AOT? Yes. `EasyEcs.Core` is marked `IsAotCompatible`, so the trimming and AOT analyzers run on every build of the library, and the generated code calls your methods directly (no reflection on hot paths; [D16](https://ecs.xgamedev.net/en/docs/decisions#d16-no-partial-generated-code-lives-outside-the-users-type)). A program built on it publishes with `PublishAot` without warnings and runs: CI publishes the battle server example, with tracked components, disabled components and saves, as a native executable with warnings as errors and runs it. One limit: a generic system closed only by another assembly falls back to `MakeGenericType`, which Native AOT cannot do ([D20](https://ecs.xgamedev.net/en/docs/decisions#d20-generic-systems-register-the-closed-types-their-assembly-names)). Deploying a server: [hosting](https://ecs.xgamedev.net/en/docs/guide/hosting#deploy). ## Why are there no events? Nothing calls your code when a component is added, removed or written ([D1](https://ecs.xgamedev.net/en/docs/decisions#d1-state-changes-are-data-no-events-or-callbacks)). A callback runs inside another system: it hides the control flow, can re-enter the code that raised it, and its reads and writes are invisible to the scheduler, so systems could not run in parallel safely. What an event would say is data instead: | The event you want | Write it as | | ----------------------------------------- | -------------------------------------------------------------- | | An entity died, others should react | a `Dead` tag; the systems that care filter `[With]` | | A component was changed | mark it `ITrackChanges`; the consumer takes `[Changed]` | | A component was removed (a buff expired) | mark it `ITrackChanges`; the consumer takes `[Removed]` | | A one-off message (a hit, a player input) | an entity holding the message, destroyed after its readers ran | | Input from another thread | a queue that one system drains on the owner thread | ```csharp public record struct Hit(EntityId Target, int Damage) : IComponent; // a message is an entity public class ApplyHitsSystem : EcsSystem { [ForEach] static void Apply(in Hit hit, World world) { if (!world.TryGetEntity(hit.Target, out var target)) return; // the target is gone ref var hp = ref target.TryGetRef(out bool found); if (found) hp = hp with { Value = hp.Value - hit.Damage }; } } [UpdateAfter] // after every reader public sealed class ClearHitsSystem : EcsSystem { protected override void OnUpdate() => World.DestroyEntities(); // every message, one pass } ``` The order of effects is the order of the systems, visible in one place; the generator knows what every system reads and writes; tests and snapshots see the "events", because they are data. ## Why are there no command buffers? Structural changes apply at once, also in the middle of a pass ([D2](https://ecs.xgamedev.net/en/docs/decisions#d2-structural-changes-apply-at-once-no-command-buffers)): a removed row becomes a tombstone while the pass runs and the pass never sees rows shift, so code reads as it is written and no second, deferred version of the world exists. Parallel jobs make no structural change; a system after them, on the owner thread, makes it from the data they wrote ([D3](https://ecs.xgamedev.net/en/docs/decisions#d3-no-command-buffer-for-parallel-jobs)). What a pass sees when you change structure inside it: [Structural changes](https://ecs.xgamedev.net/en/docs/guide/structural-changes). ## How do I order systems? Systems run in the order you register them. To make one depend on another, name the dependency: `[UpdateBefore]` or `[UpdateAfter]` on the class moves only that system within its group, so adding one ordering never reshuffles the others ([D5](https://ecs.xgamedev.net/en/docs/decisions#d5-order-systems-by-dependencies-not-priorities)). A cycle throws in `AddSystem` and is reported by EECS019 when the analyzer can see it. There are no integer priorities: `Priority` was removed in 4.1. Systems that run on a different cadence go into a [system group](https://ecs.xgamedev.net/en/docs/guide/systems) updated by its own call, or set `UpdateInterval` and `UpdatePhase`. ## How do I change a component? Through a `ref`. In a `[ForEach]` method, a `ref` parameter is a write and `in` is a read: ```csharp public record struct Poison(int DamagePerTick) : IComponent; public record struct Mana(int Value) : IComponent; public class PoisonSystem : EcsSystem { [ForEach, Without] static void Hurt(ref Health hp, in Poison poison) => hp = hp with { Value = hp.Value - poison.DamagePerTick }; } ``` Outside systems: ```csharp entity.Mana.Value -= 10; // untracked: the generated property is a ref ref var poison = ref entity.Poison; // keep the ref for several writes poison.DamagePerTick = 3; ref var mana = ref entity.TryGetRef(out bool found); // when the entity may not have it if (found) mana.Value += 5; entity.Set(new Position(0, 0), new Velocity(1, 0)); // add or replace several in one call: shorter, same cost foreach (var item in world.Query()) item.Position.X += item.Velocity.X; // refs into the row ``` Three mistakes to avoid: - `var hp = entity.Health; hp.Value--;` changes a copy. Keep a `ref var`. - Read with `in`, not `ref`: every `ref` access to an `ITrackChanges` component counts as a change, so replication would send rows nobody changed. The generated property of a tracked component is read-only for this reason; `entity.WriteX()` is the write. - Change a collection inside a component through a `ref` to the component, never through `in`: change tracking and the scheduler would miss it ([EECS011](https://ecs.xgamedev.net/en/docs/guide/analyzer)). For a list per entity, use a [`DynamicBuffer`](https://ecs.xgamedev.net/en/docs/guide/dynamic-buffers). ## How many component types can a world have? Up to 65,536 component types per process (component bits are 16-bit). The first 256 are tested with one `Vector256` instruction per table; the rest live in an overflow that is allocated when a table is first built, never on a hot path ([Architecture](https://ecs.xgamedev.net/en/docs/architecture#storage-model)). ## Do systems have to be `partial`? No. The generator writes each system's jobs in a file class of its own and calls your `[ForEach]` methods, private or not, through `[UnsafeAccessor]`, which compiles to a direct call ([D16](https://ecs.xgamedev.net/en/docs/decisions#d16-no-partial-generated-code-lives-outside-the-users-type)). A system is an ordinary class, and generated members never collide with yours. `partial` still compiles. ## Related - [What is an ECS?](https://ecs.xgamedev.net/en/docs/what-is-ecs): The pattern itself, archetype and sparse-set storage, and when an ECS fits. - [Design decisions](https://ecs.xgamedev.net/en/docs/decisions): Every non-obvious choice, what was weighed against it, and the numbers. - [Comparison](https://ecs.xgamedev.net/en/docs/comparison): EasyEcs against Friflo.Engine.ECS, Arch and DefaultEcs, feature by feature and measured. --- # 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. URL: https://ecs.xgamedev.net/en/docs/ai Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/ai.md EasyEcs is newer than most models' training data, and its rules (stateless systems, state changes as data, `in` and `ref` parameters, the owner thread) are what an assistant gets wrong first. This page shows the three ways to put the real docs in front of one: the `llms.txt` files, the Markdown copy of each page, and a rules file for your project. ## The docs as text | File | What it holds | | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | | [`/llms.txt`](https://ecs.xgamedev.net/llms.txt) | A summary of EasyEcs, its key facts and a link to the Markdown copy of every English page ([llmstxt.org](https://llmstxt.org) format) | | [`/llms-full.txt`](https://ecs.xgamedev.net/llms-full.txt) | The full text of every English page in one file | | [`/llms.zh.txt`](https://ecs.xgamedev.net/llms.zh.txt), [`/llms-full.zh.txt`](https://ecs.xgamedev.net/llms-full.zh.txt) | The same for the Chinese pages (also at `/zh/llms.txt` and `/zh/llms-full.txt`) | Give an assistant `llms.txt` when it can follow links, `llms-full.txt` when it cannot. The full file includes the code of the [battle server example](https://ecs.xgamedev.net/en/docs/example), so a model sees every feature used together. ## Markdown copies of every page Add `.md` to a page's URL for its Markdown: `https://ecs.xgamedev.net/en/docs/guide/queries.md`. The docs home is `/en/docs.md`. A request for the page itself with `Accept: text/markdown` gets the same Markdown, so tools that ask for Markdown first need no special URL: ```bash curl -H "Accept: text/markdown" https://ecs.xgamedev.net/en/docs/guide/systems ``` The menu at the top of each page copies its Markdown or opens it in ChatGPT, Claude, T3 Chat or Scira with the page attached. ## A rules file for your project [`easyecs-rules.md`](https://ecs.xgamedev.net/easyecs-rules.md) is a short file of the rules that matter when writing EasyEcs code: components and systems, method and group filters, structural changes, `entity.Run` for a request on one entity, threads and refs, performance, persistence (snapshots, saves, records with `LoadEntitiesInto`), what EasyEcs does not do (including the actor pattern it leaves to you), project layout and debugging, and an example. It is drawn from the [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles), the [analyzer rules](https://ecs.xgamedev.net/en/docs/guide/analyzer), the [performance guide](https://ecs.xgamedev.net/en/docs/performance), [project structure](https://ecs.xgamedev.net/en/docs/guide/project-structure) and [diagnostics](https://ecs.xgamedev.net/en/docs/guide/diagnostics). Download it into the `docs/` folder of your repository, where the snippets below look for it: ```bash curl -fsSL --create-dirs -o docs/easyecs-rules.md https://ecs.xgamedev.net/easyecs-rules.md ``` Then point your assistant at it. The analyzer still checks every build, so a rule the assistant misses becomes a compile error, not a bug. ### AGENTS.md Codex, Jules, Cursor, Zed and other agents read `AGENTS.md` at the repository root. Add a line that names the file: ```markdown ## EasyEcs Follow docs/easyecs-rules.md when writing code that uses EasyEcs. ``` ### Claude Code `CLAUDE.md` can import the file, so Claude Code loads it with the project instructions: ```markdown @docs/easyecs-rules.md ``` Or make it a skill that loads only when the task touches EasyEcs. A skill is a folder with a `SKILL.md` whose frontmatter tells Claude when to use it: ```text .claude/skills/easyecs/ SKILL.md frontmatter (name, description) + the rules ``` ```markdown --- name: easyecs description: Rules for writing EasyEcs code (components, systems, [ForEach], queries). Use when editing code that uses EasyEcs. --- (paste the contents of easyecs-rules.md here) ``` ### Cursor A rule in `.cursor/rules/` with `.mdc` frontmatter applies to the files its globs match: ```markdown --- description: EasyEcs rules globs: "**/*.cs" alwaysApply: false --- (paste the contents of easyecs-rules.md here) ``` ### GitHub Copilot Copilot reads `.github/copilot-instructions.md` for the whole repository, and `.github/instructions/*.instructions.md` for the files an `applyTo` glob matches: ```markdown --- applyTo: "**/*.cs" --- (paste the contents of easyecs-rules.md here) ``` ## Other tools Services that index GitHub repositories and documentation for assistants, such as [Context7](https://context7.com) and [DeepWiki](https://deepwiki.com), can be pointed at the [EasyEcs repository](https://github.com/JasonXuDeveloper/EasyEcs) from their own sites. They are run by others: check what they return against these docs, which are the source. ## Related - [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles): The rules behind the rules file. - [Getting started](https://ecs.xgamedev.net/en/docs/getting-started): The first world, systems and queries. - [FAQ](https://ecs.xgamedev.net/en/docs/faq): Short answers to common questions. --- # 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. URL: https://ecs.xgamedev.net/en/docs/decisions Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/decisions.md 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](https://ecs.xgamedev.net/en/docs/performance) and [Comparison](https://ecs.xgamedev.net/en/docs/comparison). What is planned next is on the [roadmap](https://ecs.xgamedev.net/en/docs/roadmap). | # | Decision | | --------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | [D1](https://ecs.xgamedev.net/en/docs/decisions#d1-state-changes-are-data-no-events-or-callbacks) | State changes are data: no events or callbacks | | [D2](https://ecs.xgamedev.net/en/docs/decisions#d2-structural-changes-apply-at-once-no-command-buffers) | Structural changes apply at once: no command buffers | | [D3](https://ecs.xgamedev.net/en/docs/decisions#d3-no-command-buffer-for-parallel-jobs) | No command buffer for parallel jobs | | [D4](https://ecs.xgamedev.net/en/docs/decisions#d4-no-addedt-filter) | No `Added` filter | | [D5](https://ecs.xgamedev.net/en/docs/decisions#d5-order-systems-by-dependencies-not-priorities) | Order systems by dependencies, not priorities | | [D6](https://ecs.xgamedev.net/en/docs/decisions#d6-removing-a-component-keeps-the-row) | Removing a component keeps the row | | [D7](https://ecs.xgamedev.net/en/docs/decisions#d7-contiguous-columns-not-pages) | Contiguous columns, not pages | | [D8](https://ecs.xgamedev.net/en/docs/decisions#d8-no-whole-entity-disable) | No whole-entity disable | | [D9](https://ecs.xgamedev.net/en/docs/decisions#d9-saves-are-built-in-with-nino) | Saves are built in, with Nino | | [D10](https://ecs.xgamedev.net/en/docs/decisions#d10-moveentities-copies-rows-without-encoding) | `MoveEntities` copies rows without encoding | | [D11](https://ecs.xgamedev.net/en/docs/decisions#d11-ids-in-a-prefab-name-its-members) | Ids in a prefab name its members | | [D12](https://ecs.xgamedev.net/en/docs/decisions#d12-target-policies-are-opt-in-per-index) | Target policies are opt-in, per index | | [D13](https://ecs.xgamedev.net/en/docs/decisions#d13-one-owner-thread-per-world) | One owner thread per world | | [D14](https://ecs.xgamedev.net/en/docs/decisions#d14-no-shared-components) | No shared components | | [D15](https://ecs.xgamedev.net/en/docs/decisions#d15-net-10-only) | .NET 10 only | | [D16](https://ecs.xgamedev.net/en/docs/decisions#d16-no-partial-generated-code-lives-outside-the-users-type) | No `partial`: generated code lives outside the user's type | | [D17](https://ecs.xgamedev.net/en/docs/decisions#d17-unloading-removes-types-from-worlds-bits-are-reused) | Unloading removes types from worlds; bits are reused | | [D18](https://ecs.xgamedev.net/en/docs/decisions#d18-no-interceptors-for-query-calls-filters-carry-no-references) | No interceptors for query calls; filters carry no references | | [D19](https://ecs.xgamedev.net/en/docs/decisions#d19-no-settable-tag-properties) | No settable tag properties | | [D20](https://ecs.xgamedev.net/en/docs/decisions#d20-generic-systems-register-the-closed-types-their-assembly-names) | Generic systems register the closed types their assembly names | | [D21](https://ecs.xgamedev.net/en/docs/decisions#d21-net-10-features-only-where-they-measure) | .NET 10 features only where they measure | | [D22](https://ecs.xgamedev.net/en/docs/decisions#d22-parallel-runs-use-the-thread-pool-and-wake-helpers-only-when-they-pay) | Parallel runs use the thread pool and wake helpers only when they pay | | [D23](https://ecs.xgamedev.net/en/docs/decisions#d23-change-summaries-per-block-removals-summarized-apart) | Change summaries per block; removals summarized apart | | [D24](https://ecs.xgamedev.net/en/docs/decisions#d24-an-indexs-key-holds-its-entities-in-one-array) | An index's key holds its entities in one array | | [D25](https://ecs.xgamedev.net/en/docs/decisions#d25-structural-row-loops-are-compiled-for-tables-without-tombstones) | Structural row loops are compiled for tables without tombstones | | [D26](https://ecs.xgamedev.net/en/docs/decisions#d26-generated-members-and-a-suggestion-to-use-them) | Generated members where code would repeat a type, and a suggestion to use them | | [D27](https://ecs.xgamedev.net/en/docs/decisions#d27-reading-a-missing-singleton-throws-everywhere) | Reading a missing singleton throws everywhere | | [D28](https://ecs.xgamedev.net/en/docs/decisions#d28-reservations-grow-to-what-they-need-entity-storage-on-the-pinned-heap) | Reservations grow to what they need; entity storage on the pinned heap | | [D29](https://ecs.xgamedev.net/en/docs/decisions#d29-performance-rules-only-where-the-cost-is-measured-and-the-fix-does-the-same) | Performance rules only where the cost is measured and the fix does the same | | [D30](https://ecs.xgamedev.net/en/docs/decisions#d30-saves-record-types-by-nino-type-id) | Saves record types by Nino type id; Nino writes the unmanaged components marked `[NinoType]` | | [D31](https://ecs.xgamedev.net/en/docs/decisions#d31-a-record-of-what-persists) | A record of what persists: a component set to save, loading onto existing entities | | [D32](https://ecs.xgamedev.net/en/docs/decisions#d32-the-lists-of-dead-buffers-are-pooled-per-thread) | The lists of dead buffers are pooled per thread | | [D33](https://ecs.xgamedev.net/en/docs/decisions#d33-one-entity-runs-a-passs-job) | One entity runs a pass's job: `entity.Run` | | [D34](https://ecs.xgamedev.net/en/docs/decisions#d34-group-filters-through-interfaces) | Group filters through interfaces | | [D35](https://ecs.xgamedev.net/en/docs/decisions#d35-a-record-can-load-without-counting-as-a-change) | A record can load without counting as a change | | [D36](https://ecs.xgamedev.net/en/docs/decisions#d36-not-added) | Not added: parallel batch jobs, a row's last write tick, public access sets, a shared parallelism budget | | [D37](https://ecs.xgamedev.net/en/docs/decisions#d37-the-easyecs-package-brings-ninos-generator) | The EasyEcs package brings Nino's generator | | [D38](https://ecs.xgamedev.net/en/docs/decisions#d38-the-hidden-columns-are-not-generic-over-their-component) | The hidden columns are not generic over their component | | [D39](https://ecs.xgamedev.net/en/docs/decisions#d39-a-whole-load-can-leave-the-change-ticks-alone) | 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]`, `[Removed]`). **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: ```csharp 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] public class DeathSystem : EcsSystem { [ForEach, Without] // 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` filter **Decision.** There is no filter for "gained `T` since a tick". `[Changed]` 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: ```csharp public struct Spawned : IComponent; // a tag: "new since the last Greet" public class GreetSystem : EcsSystem { [ForEach, With, With] static void Greet(Entity entity) => entity.RemoveSpawned(); // first-time work, then a bit flip } ``` ```csharp world.CreateEntity(new Health(100), new Spawned()); // the creator says it is new ``` **Why.** 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`, DefaultEcs' `WhenAdded` (on the 4.1 roadmap, dropped before implementation). ## D5. Order systems by dependencies, not priorities **Decision.** Systems run in registration order. `[UpdateBefore]` / `[UpdateAfter]` 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]` 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` do it explicitly; `Disable()` keeps one component's value while hiding it: ```csharp public struct Inactive : IComponent; // the whole entity is off public struct Bullet : IComponent; public class BulletSystem : EcsSystem { [ForEach, With, Without] // 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); } ``` ```csharp 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(QueryFilter.Create().With()); // saves, cleanup, stats see everything ``` Uses: 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]` 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** | 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 | BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS. ## 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()`). ## 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](https://ecs.xgamedev.net/en/docs/guide/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().Without().Without()` 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>()`, `new CountOf()`, a base type `CountOf`, 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`) | kept: a table without tombstones counts the set bits of its row words, 8 words per step with AVX-512, else `Vector` (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` 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` pass finds the next written word with one bit scan; a `Removed` 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(params ReadOnlySpan)`. The analyzer suggests the generated member wherever code calls the generic API (EECS033, Info, with a code fix): `entity.Get()` as `entity.Position`, `Has()` as `HasX` or `IsX`, `Set(new T(…))` as `SetX(…)`, `GetSingleton()` as `world.X`, `Index()` 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..n` makes 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()` of a tracked component, whose property is `ref readonly`, becomes `WriteX()` (an indexed component has no writer, so its `Get()` keeps its spelling). A buffer's members exist only while code names `DynamicBuffer`, 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()`, `RemoveAll()` 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.Value` as `world.X`.** A `SingletonRef` 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()`, `SingletonRef()`, 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()`, or `GetOrAddClock()` where a default is meant). `GetOrAddSingleton()` / `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 while `world.X` threw. A world built without its `SetClock(...)` 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 first `Update()` names the singleton and the call to add. - **One rule for every read.** The same singleton read in `OnUpdate` and taken as a parameter behaved differently; now a read is a read, and only a call named `GetOrAdd` adds. - **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`, `LoadEntities` or 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 a `Load` brings 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(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_GCLOHThreshold` raised). .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.GetGenerationBudget` in 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` for entities created one by one.** `EnsureEntityCapacity` sized 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 with `EnsureCapacity` on its store and archetype: 11 to 12 ms; Arch with `EnsureCapacity`: 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()` 258 µs, a parameter 40 µs; `Has()` 208 µs, `Maybe` 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](https://ecs.xgamedev.net/en/docs/performance#dont) 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](https://ecs.xgamedev.net/en/docs/decisions#d28-reservations-grow-to-what-they-need-entity-storage-on-the-pinned-heap)); `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()` test in the loop 332 µs, a filter 59.5 µs | | EECS033 the generated member | Info | the same call, the same cost ([D26](https://ecs.xgamedev.net/en/docs/decisions#d26-generated-members-and-a-suggestion-to-use-them)) | | 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, `++`, a `ref` or `out` argument, a method that is not `readonly`, a `ref` local and a `this ref` extension as a write; EECS027 reports only lookups made on every row, of components the method does not change itself; EECS028 leaves out `throw`, `[Conditional]` calls, console output, and the `OnUpdate` of a system with its own `UpdateInterval`; EECS030 leaves out a `Set` that overwrites a component the query requires and one of a grouped component (its rows move one by one in `SetAll` too); 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 reports `Count` compared 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 `Any` and 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 `ref` to the method means no fix. **Considered.** - **Several components added or removed one call at a time** (`e.Set(a); e.Set(b);` as `e.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]`**: 37.7 against 38.6 µs; what costs is the access it declares, which EECS026 already reports for any unused parameter. - **`[Changed]` of an untracked component**: the attribute's constraint already fails it (CS0315). - **`Parallel = true` on 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]` costs nothing. - **`World.Update` from 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 `Query` loops in `OnUpdate`, `Capture` or `Describe` on the hot path, value index lookups in loops**: `Query` is 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 `QueryFilter` built per call instead of kept in a `static readonly` field**: a filter is a small struct with no references ([D18](https://ecs.xgamedev.net/en/docs/decisions#d18-no-interceptors-for-query-calls-filters-carry-no-references)); 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 (`VersionTolerant` appended members, `Keyed` any 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](https://ecs.xgamedev.net/en/docs/migration#v4-4-saves) 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()`, `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; `LoadEntities` would create a second entity and rewrite the record's `EntityId` fields 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 `Set` of 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, and `EntityId` fields that name the temporary one. ## D32. The lists of dead buffers are pooled per thread **Decision.** A `DynamicBuffer` 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(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 `Run` as a structural call ([EECS010](https://ecs.xgamedev.net/en/docs/guide/analyzer#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` or `IGroupWithout`, itself or through one of its interfaces, gets the same filter as `[With]` / `[Without]` 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>]` cannot sit on `IActorGroup`. 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` / `Without` of 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` filters by `In`). **Considered.** - **A `Type` argument 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]` 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()`.** `entity.Run(ref job, QueryFilter.Create().Changed(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.MaxDegreeOfParallelism` per 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 `Save` threw at run time. - **No drift.** The generator always matches the runtime EasyEcs was built with; an older explicit reference fails restore with `NU1605` instead of compiling against another Nino. - **Little cost.** In a project without `[NinoType]` types the generator writes one empty internal registry. **Considered.** - **Keeping `Nino.Serialization` and 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` stays: its bit is the tag bit of `T`. **Why.** - **Native AOT without warnings.** Registering `ChangeTicks` through the same generic path as a component made the AOT compiler see `ChangeTicks>` (and `Disabled>`) without end: IL3054 in every program with a tracked component, the built-in `ChildOf` included, 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]` 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. - **`changesFromNow` covers 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 - [ECS principles](https://ecs.xgamedev.net/en/docs/ecs-principles): The rules most of these decisions follow from. - [Architecture](https://ecs.xgamedev.net/en/docs/architecture): The structures these decisions shaped. - [Roadmap](https://ecs.xgamedev.net/en/docs/roadmap): What is planned, and what was dropped. --- # Roadmap > What is planned for EasyEcs, how each change is proven, and the features that were weighed and dropped, with links to the decisions. URL: https://ecs.xgamedev.net/en/docs/roadmap Version: EasyEcs 4.6 Last updated: 2026-10-20 中文版: https://ecs.xgamedev.net/zh/docs/roadmap.md What is planned, in order. An item leaves this page when it ships: the [changelog](https://ecs.xgamedev.net/en/docs/changelog) and the guides describe it from then on. A dropped item stays here as one line, its reasons in the [design decisions](https://ecs.xgamedev.net/en/docs/decisions). Every performance item is proven with BenchmarkDotNet before and after, and ships only as a net win in time and allocations. ## Planned ### Less code through the generator The generator already writes `entity.Health`, `HasHealth`, `SetHealth(…)`, `IsDead`, singleton members, `world.XIndex`, buffer members, named query items, prefab buffer writers, jobs and access sets. Before each release the API, the [battle server](https://ecs.xgamedev.net/en/docs/example) and the guides are scanned again: every line users write twice is a candidate for a generated member, and every generated member nobody uses goes. A candidate ships when it saves lines in real code at no cost per call; one that only changes style is rejected ([D26](https://ecs.xgamedev.net/en/docs/decisions#d26-generated-members-and-a-suggestion-to-use-them)). ### Toolchain and runtime The floor is the .NET 10 SDK (C# 14, Roslyn 5.0), which the generator builds against. EasyEcs moves to a newer runtime feature only where it measures ([D21](https://ecs.xgamedev.net/en/docs/decisions#d21-net-10-features-only-where-they-measure)). ## Dropped - `Added`: `[Changed]` selects added rows too; a tag the reacting system removes tells new from written ([D4](https://ecs.xgamedev.net/en/docs/decisions#d4-no-addedt-filter)). - Command buffers for parallel jobs: a parallel job writes data, a system after it changes structure ([D3](https://ecs.xgamedev.net/en/docs/decisions#d3-no-command-buffer-for-parallel-jobs)). - Interceptors for query call sites: the call's arguments are still evaluated, so a filter built at the call is built anyway ([D18](https://ecs.xgamedev.net/en/docs/decisions#d18-no-interceptors-for-query-calls-filters-carry-no-references)). `AddEmbeddedAttributeDefinition`: the generators write no attribute types (the attributes are EasyEcs.Core's). - Settable tag properties (`entity.IsDead = true`): C# 14 rejects assigning an extension property of a struct on a `foreach` variable, an indexer result or a field of an `in` parameter, where ECS code holds its entities ([D19](https://ecs.xgamedev.net/en/docs/decisions#d19-no-settable-tag-properties)). - A flat `[InlineArray]` memo, `FrozenDictionary` for saved types, `OverloadResolutionPriority`, `field`: measured or weighed, no net win ([D21](https://ecs.xgamedev.net/en/docs/decisions#d21-net-10-features-only-where-they-measure)). - Multi-type `Disable` / `Enable` and bulk calls ([D26](https://ecs.xgamedev.net/en/docs/decisions#d26-generated-members-and-a-suggestion-to-use-them)). - A generated `world.AddSystems()`: systems run in registration order, so the list is the tick's order and is read where the world is built. - Singletons added when a read finds them missing (`world.X`, `GetSingleton()`, a `[ForEach]` parameter): a missing singleton is a forgotten setup, and its default is rarely right (a clock with no step), so every read throws; `GetOrAddX()` adds the default where one is meant ([D27](https://ecs.xgamedev.net/en/docs/decisions#d27-reading-a-missing-singleton-throws-everywhere)). - Cached filters from attributes, counting members per component (`world.CountPlayer()`) and a named `TryGetXRef`: no line saved, more surface. - Parallel batch jobs, `entity.LastWriteTick()`, public access sets and one parallelism budget for several worlds ([D36](https://ecs.xgamedev.net/en/docs/decisions#d36-not-added)). ## Related - [Design decisions](https://ecs.xgamedev.net/en/docs/decisions): Why each choice was made, and why the dropped items were dropped. - [Changelog](https://ecs.xgamedev.net/en/docs/changelog): What shipped, release by release.