Fomenko

Tip #1: Compare squared distances, not lengths

By Alexandre Chêne|August 10, 2025

A vector magnitude is a few adds and multiplies, but crucially a square root; and that last bit is expensive, particularly when you’re doing it inside a loop over thousands of entities, possibly multiple times per frame.

In reality, we use a vector’s magnitude in lots of different contexts. For example (and this happens a lot), grabbing the entity closest to the player, like this:

length :: (using in: Vector3) -> float {
    return sqrt(x * x + y * y + z * z);
}

closest_dist   := MAX_FLOAT32;
closest_entity : *Entity = null;

for entities {
  dist := length(player.position - it.position);

  if dist < closest_dist {
    closest_dist    = dist;
    closest_entity  = it;
  }
}

if closest_entity != null {
  // do something with the closest entity.
}

Here, we compute the vector’s magnitude only for a value comparison, checking whether it’s smaller or larger than the current recorded minimum distance.

What we actually want is the ordering, how one value (the magnitude) relates to others; we don’t care about its intrinsic value.

So we can just use the squared magnitude; for our comparison it’s much cheaper because we completely skip the square root.

It’s a handy (and classic) trick that really helped my algorithm for detecting collisions between a capsule and large triangle soup. Now that I’m aware of this, I’ll be more mindful of operations that seem simple enough to ignore, like normalizing vectors where you divide each component by the vector’s length, which requires a square root, so we want to do that only if needed.

–––
Don't hesitate to reach out on bluesky or via twitter.