This gamedev.stackexchange question uses this library for a grid-based spatial hash. I wanted to recreate the demo in the question — given a location, find all objects that would be visible near the player. Try dragging the rectangle that represents the area visible to the player:
It sometimes catches circles that aren’t in the area of interest. Why? Grid-based approaches effectively enlarge the area of interest first to fit the grid, then find all circles that are in those grid squares.
I also tried with the rbush library, which uses an r-tree instead of a grid, and isn’t subject to the same imprecision:
However, notice that if you change the position even slightly, the r-tree may return different results, whereas with the grid, it will often be the same results. That makes the grid results more cacheable.
Which should you use? It depends on the project! Mikola Lysenko compared algorithms including grids and r-trees. He writes, “it is important to remember that when grids work they are effectively optimal”. He also compared libraries and speaks highly of rbush. Also see Bob Nystrom’s Game Programming Patterns book, which has a chapter on spatial partitioning, covering access patterns and tradeoffs between different styles of data structures.