2026-11-24

quadtrees

I ran into performance issues in some of my simulations. The agents and particles in them do a lot of neighbor comparisons, and in the worst case the update step turns into N2N^2 checks. Intuitively, a particle does not need to know about every other particle to update its own behavior, only the ones near it. With this in mind, a QuadTree lets us bring the number of checks down from N2N^2 to roughly Nlog⁡2NN \log_2 N for building and querying the tree. In practical terms a system with 1000 particles can run more than 100 times faster, depending on how dense the particles are and how big the query radius is.

A QuadTree is a tree-like data structure that divides a 2D space into rectangular regions, where each region can split into 4 child regions once it holds too many particles. Instead of keeping every particle in one flat list, we keep them in a structure that mirrors where they are in space. This drastically reduces the neighbor search space. Take for example a simulation where the 3 closest neighbors of a particle dictate its behavior. Checking every particle to find them is expensive and redundant. With a QuadTree we only check the particles in nearby regions.

QuadTrees have two primary functions: insert and query. Insertion puts a particle into the correct region. Each region has a set number of particles it can contain (I use 8 or 16). Once a region reaches its max capacity it subdivides into 4 child regions. From there you can either redistribute its particles into the children or leave them and keep inserting new particles further down. Querying is a traversal from the root. Subtrees that don't intersect the queried range are skipped. For the ones that do, we check the particles in that region and recurse into its children. This gives roughly log⁡2(N)+K\log_2(N) + K per query, where KK is the number of particles returned.

0.0 ms