EasyEcs

Indexes and relations

Find entities by a value (a name, a zone, a score range) or by the entity they point at, with IIndexed<TKey> and IRelation indexes kept current.

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<TKey> 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 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<TKey>: Key is the value the entity is found by. world.Index<T, TKey>() creates the index on first use; the generated world.XIndex property returns the same one.

public record struct Callsign(string Value) : IComponent, IIndexed<string>
{
    public string Key => Value;
}
public record struct Zone(int Id) : IComponent, IIndexed<int>
{
    public int Key => Id;
}
var alpha = world.CreateEntity(new Callsign("alpha"), new Zone(1));
world.CreateEntity(new Callsign("bravo"), new Zone(1));

var zones = world.ZoneIndex;                        // world.Index<Zone, int>(): 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<T>() 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). 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:

public readonly record struct Shop(long Id) : IComponent, IIndexed<Shop>
{
    Shop IIndexed<Shop>.Key => this;          // explicit: a public Key property would recurse in ToString()
}
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 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<TKey>: a score, a level, a deadline), the same index walks in key order:

CallVisits
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
public record struct Score(int Points) : IComponent, IIndexed<int>
{
    public int Key => Points;
}
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): the id is 8 bytes, unmanaged and saved with the world, and a handle converts to it implicitly.

public record struct OwnedBy(EntityId Owner) : IComponent, IIndexed<EntityId>
{
    public EntityId Key => Owner;
}
public struct Arrow : IComponent;
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.

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<T>, and world.Relations<T>() finds the entities linking to a target.

public record struct MemberOf(EntityId Target) : IRelation;
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<MemberOf>();                    // 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<MemberOf>(blue);
knight.RemoveRelation<MemberOf>(blue);                         // leaves blue

AddRelation adds the buffer if the entity has none, then appends the link and indexes it. Read the links with Read<DynamicBuffer<T>>() 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).

Once some code names DynamicBuffer<MemberOf> (a [ForEach] parameter, a Read), the generator adds named members for the relation:

GeneratedSame as
e.AddMemberOf(target)e.AddRelation(new MemberOf(target)), returns the entity
e.RemoveMemberOf(target)e.RemoveRelation<MemberOf>(target), returns how many links went
e.LinksMemberOf(target)e.HasRelation<MemberOf>(target)
e.MemberOf / e.HasMemberOf / e.RemoveMemberOf()the links (ref readonly DynamicBuffer<MemberOf>), whether it has any, drop them all
world.MemberOfIndexworld.Relations<MemberOf>()
public record struct PartyCount(int Parties) : IComponent;

public class CountParties : EcsSystem
{
    [ForEach]
    static void Count(in DynamicBuffer<MemberOf> parties, ref PartyCount count) => count = new PartyCount(parties.Count);
}
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:

TargetPolicyThe links to a destroyed entityExample
Keep (the default)stay, findable by the dead id (which no later entity has); a system of yours cleans theman audit trail
Removego: the component is removed from its entities, a relation drops the linksan owner loses its pet
Destroythe linking entities are destroyed too, and what links to them in turna summon dies with its summoner
world.OwnedByIndex.WhenTargetDestroyed(TargetPolicy.Destroy);       // arrows go with their archer
world.Relations<MemberOf>().WhenTargetDestroyed(TargetPolicy.Remove); // a disbanded party leaves no links

archer.Destroy();
int arrowsLeft = world.Count<Arrow>();                              // 0

WhenTargetDestroyed is set per world and per index. ChildOf, the 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.

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<Health>(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.

It prints:

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 ofDoWhy
world.Index<T, TKey>() in a hot loopKeep 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 hasCompare 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 keyFind(key) / Count(key)O(1), then O(1) per match
Sorting a query's results each tickRange / DescendingThe keys stay sorted as they change
Walking many big keys wholeGroupByA 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):

CaseMeanvs baselineAllocated
TradeAndCount5.28 μs—0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
CaseMeanvs baselineAllocated
FollowAndCount22.7 μs—0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
CaseMeanvs baselineAllocated
Ordered75.8 μs1.00×0 B
Scan307 μs4.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

MistakeWhat happensCaught by
Writing an indexed component through ref, Get<T>() or a query itemThe index keeps the old keyEECS015
Storing an Entity handle in a componentA managed column, write barriers, not savedEECS017
Changing the indexed component inside a Find loop over itThe walk can read another key's entities (destroying entities is fine)Code review: collect first, then change
A public Key => this on a record structToString() prints Key forever: a stack overflowCode review: Shop IIndexed<Shop>.Key => this;
Using an index from another threadIndexes belong to the owner threadThreading
Indexing one component by two key typesInvalidOperationException: one index per componentAt run time
A null key (the default of a string)The entity is indexed nowhereBy design

Compared with other libraries

Friflo indexes components (IIndexedComponent) and links (ILinkComponent, ILinkRelation); DefaultEcs has EntityMultiMap<T>; 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

  • EasyEcs
  • Other libraries
EasyEcs: Index0 B allocated5.11 μsFriflo.Engine.ECS: Links1.63× · 0 B allocated8.33 μsDefaultEcs: MultiMap1.54× · 0 B allocated7.87 μs0.00 ns2.00 μs4.00 μs6.00 μs8.00 μ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
EasyEcsIndex5.11 μs1.00×0 B
Friflo.Engine.ECSLinks8.33 μs1.63×0 B
DefaultEcsMultiMap7.87 μs1.54×0 B

Friend lists: 100 players change whom they follow, then 100 follower lists are read

  • EasyEcs
  • Other libraries
EasyEcs: Relations0 B allocated22.0 μsFriflo.Engine.ECS: LinkRelations1.19× · 0 B allocated26.1 μs0.00 ns5.00 μs10.0 μs15.0 μs20.0 μs25.0 μ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
EasyEcsRelations22.0 μs1.00×0 B
Friflo.Engine.ECSLinkRelations26.1 μs1.19×0 B

Ranges and a zone lookup, with the zone as a value index and as a group:

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