A Sparse-Set ECS
The toy ECS in the previous lesson gave every entity a slot in every component array. With 100,000 entities and 60 component types that is six million mostly empty slots, and a system still has to visit all of them. A sparse set fixes both problems. It is the storage behind EnTT, and it is simple enough to write in an afternoon.
The data structure
A sparse set for one component type keeps three arrays:
| Array | Indexed by | Holds |
|---|---|---|
sparse |
entity ID | position of that entity in dense, or "none" |
dense |
packed position | entity ID |
data |
packed position | the component value |
dense and data are always packed with no holes, so a system iterates them like a plain vector. sparse gives O(1) lookup from an entity to its component. Removal uses swap-and-pop: move the last element into the hole, fix its sparse entry, shrink by one.
#include <cstdint>
#include <iostream>
#include <limits>
#include <vector>
using Entity = std::uint32_t;
constexpr std::uint32_t kNone = std::numeric_limits<std::uint32_t>::max();
template <typename T>
class SparseSet {
public:
bool contains(Entity e) const { return e < sparse_.size() && sparse_[e] != kNone; }
T& add(Entity e, T value) {
if (e >= sparse_.size()) sparse_.resize(e + 1, kNone);
sparse_[e] = static_cast<std::uint32_t>(dense_.size());
dense_.push_back(e);
data_.push_back(value);
return data_.back();
}
void remove(Entity e) {
std::uint32_t hole = sparse_[e];
std::uint32_t last = static_cast<std::uint32_t>(dense_.size() - 1);
dense_[hole] = dense_[last]; // move the last element into the hole
data_[hole] = data_[last];
sparse_[dense_[hole]] = hole; // fix the moved entity's index
dense_.pop_back(); data_.pop_back();
sparse_[e] = kNone;
}
T& get(Entity e) { return data_[sparse_[e]]; }
std::size_t size() const { return dense_.size(); }
const std::vector<Entity>& entities() const { return dense_; }
std::vector<T>& values() { return data_; }
void dump(const char* label) const {
std::cout << label << " dense=[";
for (std::size_t i = 0; i < dense_.size(); i++) std::cout << (i ? " " : "") << dense_[i];
std::cout << "] data=[";
for (std::size_t i = 0; i < data_.size(); i++) std::cout << (i ? " " : "") << data_[i];
std::cout << "]\n";
}
private:
std::vector<std::uint32_t> sparse_;
std::vector<Entity> dense_;
std::vector<T> data_;
};
int main() {
SparseSet<int> health;
health.add(7, 70);
health.add(2, 20);
health.add(9, 90);
health.add(4, 40);
health.dump("after adds: ");
health.remove(2);
health.dump("remove 2: ");
std::cout << "contains 2? " << health.contains(2) << ", health of 4 = " << health.get(4) << "\n";
}after adds: dense=[7 2 9 4] data=[70 20 90 40]
remove 2: dense=[7 4 9] data=[70 40 90]
contains 2? 0, health of 4 = 40
Removing entity 2 moved entity 4 (the last one) into its slot. Order inside a sparse set is not stable, which is fine for systems that treat every entity the same way.
A registry and a two-component view
A registry owns one sparse set per component type and hands out entity IDs. A view over <Position, Velocity> iterates the smaller of the two sets and checks the other with contains. That is the trick that makes sparse-set queries cheap: the loop length is the size of the rarest component, not the number of entities.
#include <algorithm>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <typeindex>
#include <unordered_map>
#include <vector>
using Entity = std::uint32_t;
constexpr std::uint32_t kNone = std::numeric_limits<std::uint32_t>::max();
struct IPool { virtual ~IPool() = default; virtual void remove(Entity) = 0; virtual bool contains(Entity) const = 0; };
template <typename T>
struct Pool : IPool {
std::vector<std::uint32_t> sparse;
std::vector<Entity> dense;
std::vector<T> data;
bool contains(Entity e) const override { return e < sparse.size() && sparse[e] != kNone; }
void add(Entity e, T v) {
if (e >= sparse.size()) sparse.resize(e + 1, kNone);
sparse[e] = static_cast<std::uint32_t>(dense.size());
dense.push_back(e); data.push_back(v);
}
void remove(Entity e) override {
if (!contains(e)) return;
std::uint32_t hole = sparse[e], last = static_cast<std::uint32_t>(dense.size() - 1);
dense[hole] = dense[last]; data[hole] = data[last];
sparse[dense[hole]] = hole;
dense.pop_back(); data.pop_back(); sparse[e] = kNone;
}
T& get(Entity e) { return data[sparse[e]]; }
};
class Registry {
public:
Entity create() { return next_++; }
template <typename T> void emplace(Entity e, T v) { pool<T>().add(e, v); }
template <typename T> T& get(Entity e) { return pool<T>().get(e); }
void destroy(Entity e) { for (auto& [type, p] : pools_) p->remove(e); }
// Calls fn(entity, A&, B&) for every entity that has both components.
template <typename A, typename B, typename Fn>
void each(Fn fn) {
Pool<A>& a = pool<A>(); Pool<B>& b = pool<B>();
if (a.dense.size() <= b.dense.size()) {
for (std::size_t i = 0; i < a.dense.size(); i++) { Entity e = a.dense[i]; if (b.contains(e)) fn(e, a.data[i], b.get(e)); }
} else {
for (std::size_t i = 0; i < b.dense.size(); i++) { Entity e = b.dense[i]; if (a.contains(e)) fn(e, a.get(e), b.data[i]); }
}
lastScan_ = std::min(a.dense.size(), b.dense.size());
}
std::size_t lastScan() const { return lastScan_; }
private:
template <typename T> Pool<T>& pool() {
auto& slot = pools_[std::type_index(typeid(T))];
if (!slot) slot = std::make_unique<Pool<T>>();
return static_cast<Pool<T>&>(*slot);
}
Entity next_ = 0;
std::size_t lastScan_ = 0;
std::unordered_map<std::type_index, std::unique_ptr<IPool>> pools_;
};
struct Position { double x, y; };
struct Velocity { double x, y; };
int main() {
Registry reg;
for (int i = 0; i < 1000; i++) { // 1000 static props
Entity e = reg.create();
reg.emplace(e, Position{double(i), 0});
}
Entity a = reg.create(), b = reg.create(), c = reg.create();
reg.emplace(a, Position{0, 0}); reg.emplace(a, Velocity{1, 0});
reg.emplace(b, Position{5, 5}); reg.emplace(b, Velocity{0, -2});
reg.emplace(c, Position{9, 1}); reg.emplace(c, Velocity{-1, 1});
auto move = [&](double dt) {
reg.each<Position, Velocity>([dt](Entity, Position& p, Velocity& v) { p.x += v.x * dt; p.y += v.y * dt; });
};
move(0.5);
std::cout << "view scanned " << reg.lastScan() << " entries out of " << 1003 << " positions\n";
reg.destroy(b);
move(0.5);
std::cout << std::fixed << std::setprecision(2);
reg.each<Position, Velocity>([](Entity e, Position& p, Velocity&) {
std::cout << "entity " << e << " at (" << p.x << ", " << p.y << ")\n";
});
}view scanned 3 entries out of 1003 positions
entity 1000 at (1.00, 0.00)
entity 1002 at (8.00, 2.00)
The movement system touched 3 entries, not 1003, because it walked the Velocity set. Destroying b removed it from every pool it was in.
Where sparse sets shine and where they don't
| Strength | Weakness |
|---|---|
| Adding and removing a component is O(1) and moves nothing else | A query over several components does a contains check and a random-access get per hit |
| Each component type is stored independently, so iterating one type is perfectly linear | The components of one entity are scattered over many arrays |
| Easy to write, easy to debug | Large sparse arrays when entity IDs are big (real libraries page them) |
EnTT reduces the multi-component cost with groups, which keep several pools sorted so that matching entities sit at the same indices. Archetype ECSes take the opposite trade-off, covered in An Archetype ECS.
Note: Real entity IDs also carry a version (generation) so a stale ID for a destroyed and reused slot is detected. Our
Entityis a bare index to keep the code short; see Generational Handles for how to add it.
Tip: Never hold a
T&from a pool across anemplaceof the same type:push_backmay reallocate the vector and the reference dangles. Store the entity and look the component up again.
Test yourself
What does the sparse array of a sparse set map?
- Packed index → entity
- Entity ID → packed index in the dense array
- Component type → pool
- Entity → list of component types
How does swap-and-pop removal keep the dense array packed?
- It shifts every later element left by one
- It moves the last element into the removed slot and updates that element's sparse entry
- It marks the slot as free and leaves a hole
- It sorts the array
A view over <Position, Velocity> with 10,000 positions and 50 velocities iterates about how many entries?
- 10,050
- 10,000
- 50
- 500,000