EasyEcs

Dynamic buffers

DynamicBuffer<T> 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.

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<T> 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<DynamicBuffer<T>>] 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, 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<Loot> is the component.

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<T>() holds no list yet. Each entity gets its own list on its first write, so one value can create a whole wave of entities.

var players = new Entity[1_000];
world.CreateEntities(players, new DynamicBuffer<Loot>(), 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.

Pickup.cs
public class Pickup : EcsSystem
{
    [ForEach, With<Player>]
    static void Collect(ref DynamicBuffer<Loot> 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<DynamicBuffer<Loot>>] method visits only the bags written since its system last ran. It reads them with in, which is not a write.

SendBags.cs
public class SendBags : EcsSystem
{
    [ForEach, Changed<DynamicBuffer<Loot>>] 
    static void Send(in DynamicBuffer<Loot> bag, ref Sent sent)
    {
        int items = 0;
        foreach (var loot in bag) items += loot.Item;
        sent = new Sent(items);
    }
}
world.AddSystem<Pickup>();
world.AddSystem<SendBags>();
world.Update();

Choosing how to hold a list

The listHold it as
Plain values only its owner uses, sent or saved when it changes: item ids or stacks, waypoints, the hits of a tickDynamicBuffer<T>
Items with state of their own (durability, buffs with timers) that systems query or change one by oneOne entity per item with an EntityId link 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.

Reading and writing

Read (in, Read<T>(), or a ref)Write (a ref only: a ref parameter, Get<T>(), TryGetRef<T>)
Count, Capacity, bag[i] (read-only), AsReadOnlySpan(), foreachAdd, AddRange, Insert, RemoveAt, RemoveAtSwapBack, Clear, EnsureCapacity, TrimExcess, AsSpan() (writable)

The writes are extension methods on ref DynamicBuffer<T>, so the compiler rejects them on an in parameter or on Read<T>(): 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<Loot>, the generator writes named members:

GeneratedSame as
e.Loote.Read<DynamicBuffer<Loot>>(): a ref readonly, not stamped
e.HasLoote.Has<DynamicBuffer<Loot>>()
e.WriteLoot()e.Get<DynamicBuffer<Loot>>(): a ref, stamped as written
e.GetOrAddLoot()e.GetOrAdd<DynamicBuffer<Loot>>(): adds an empty buffer first if missing
e.RemoveLoot()e.Remove<DynamicBuffer<Loot>>()
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<Loot> 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.

Copies

The list lives in an object the component refers to. A copy of a DynamicBuffer<T> 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):

public static class Bags
{
    public static int Items(Entity player)
    {
        var copy = player.Read<DynamicBuffer<Loot>>();   // 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<T>() (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 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 gets its elements with SetBuffer(...):
var chest = new Prefab().SetBuffer(new Loot(1), new Loot(2));
var opened = world.Instantiate(chest);                        // its own list: Loot 1, Loot 2
  • Save 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.

It prints:

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 ofDoWhy
Letting a list grow from emptyEnsureCapacity(n) once where the size is knownAdding within the capacity allocates nothing
A new list per tickClear() and refillClear keeps the capacity: a list refilled every tick allocates nothing once it reached its size
RemoveAt(i) when the order does not matterRemoveAtSwapBack(i)O(1) instead of O(count)
Reading through a ref parameterAn in parameterA ref stamps the row, and every [Changed<T>] reader visits it (EECS025)
Keeping a span across AddTake a new span after any call that may grow the listAdd, 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<T> in a tracked component:

CaseListMeanvs baselineAllocated
TickFalse56.5 μs—0 B
TickTrue61.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.

CaseMeanvs baselineAllocated
LoadAndUnload76.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.
  • 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<T>: each chunk writes only its own entities' lists.

Pitfalls

MistakeWhat happensCaught by
Copying the buffer into a local, a field or another entityTwo owners of one list; writes through the copy are not trackedEECS012
Calling Add on an in parameter or on Read<T>()Does not compile: the writes need a refThe compiler
Keeping an AsSpan() across an AddThe span still points at the old arrayCode review: take a new span
Reading the buffer through a ref parameterEvery visited row counts as changedEECS025
One entity per element of a plain listAn entity, a row and an index entry per itemUse a buffer for plain values
Edit on GitHub

Last updated on

How is this guide?

On this page