EasyEcs

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.

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<T>() splits the world's tables by the value of an IGroup component, so entities of one group share tables of their own. QueryFilter.InGroup<T>(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<T>], World.Update<T>()) are another feature: see 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. Values that change every tick: each change moves the row. A world per partition when the partitions never interact: 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.

public record struct Zone(int Id) : IComponent, IGroup
{
    public int Group => Id;
}

Group the world at setup

GroupBy<T>() 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.

world.GroupBy<Zone>();                                         // 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<T>(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.

public struct SumHealth : IForEach<Health>
{
    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);
}
int inOne = world.Count<Health>(Zones.One);                   // 3
var sum = new SumHealth();
world.ForEach<Health, SumHealth>(ref sum, Zones.One);          // a struct job over zone 1 only
foreach (var item in world.Query<Health>(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.

var walker = world.CreateEntity(new Zone(1), new Health(50));
walker.SetZone(2);                                             // now walked by InGroup<Zone>(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). 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:

public record struct ActiveZone(int Id) : ISingletonComponent;

public struct Regenerate : IForEach<Health>
{
    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<Health, Regenerate>(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

OperationLands in
CreateEntity, CreateEntitiesthe group of the value, directly (no move)
Set, SetAll of the grouped componentthe new value's group (one row copy if it changed)
Instantiate(prefab), Clone(), LoadEntities, MoveEntitiesthe 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<T>(), every table holds group 0: InGroup<T>(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.

It prints:

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<T>() 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):

CaseMeanvs baselineAllocated
Group47.4 μs1.01×0 B
Index138 μs2.93×0 B
Scan742 μs16×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

MistakeWhat happensCaught by
Writing the grouped component through a refThe row stays in its old groupEECS015
A group per player, guild or ownerA table per key: memory and fragmentationUse a value index
A value that changes every tickA row copy per changeKeep it a plain component
Two InGroup calls in one filterA filter holds one group: the last one counts, and both components are still requiredCode review
GroupBy during a passThrows: it moves rowsCall 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

  • EasyEcs
  • Other libraries
EasyEcs: Group0 B allocated127 μsEasyEcs: Index1.83× · 0 B allocated233 μsFriflo.Engine.ECS: IndexedComponent2.49× · 0 B allocated317 μs0.00 ns50.0 μs100 μs150 μs200 μs250 μs300 μs350 μsTime (shorter is faster)

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

Data table
LibraryCaseMeanvs EasyEcsAllocated
EasyEcsGroup127 μs1.00×0 B
EasyEcsIndex233 μs1.83×0 B
Friflo.Engine.ECSIndexedComponent317 μs2.49×0 B
Edit on GitHub

Last updated on

How is this guide?

On this page