Vector*.Distance Performance

I’m starting to do a fair amount of distance checks and normally I’d just use the squared Distances but for some of these checks I need the actual distance. Is the built-in Distance function as fast as something I could write myself. I’m aware of some sqrt approximations that might speed things up but I won’t bother if Unity is reasonable fast.

I don’t have Unity pro so I can’t really instrument and test this and stress testing seems inconclusive so far.

1 Like

Distance is probably faster than anything you can write yourself. The docs say “Vector3.Distance(a,b) is the same as (a-b).magnitude”, but (a-b).magnitude is actually about 25% slower than using Distance, at least on my machine (quad-core Xeon). In fact, Distance isn’t actually that much slower than (a-b).sqrMagnitude. (I should also mention a while ago I made an “optimized” square root approximation, but Mathf.Sqrt was actually faster, so I gave up on that…)

Performance Strongly depend on the platform you are on. As someone mentioned the FPU makes a big difference.

One PC I see Vector3.Distance and Vector3.sqrMagnitude having the same performance. Both faster than Vector3.magnitude.
86761-distanceperformancepc.png

On mobile (Android Nexus 7) Vector3.Distance is 6X SLOWER that Vector3.sqrMagnitude.
86760-distanceperformanceandroid.png

So it depends on the platform you are working on. If you are considering releasing on mobile sqrMagnitude is your safest bet.

The floating point coprocessor (FPU) inside modern CPUs already have direct square root instructions. Don’t mind: these FPUs are fast, incredibly fast. There’s no chance to write something faster than a single instruction square root (except look-up tables, and only in some very special cases).

My tests show that Vector2.Distance is the same as Vector3.Distance.
(vector2 - vector2).sqrMagnitude is about 170% faster than vectorX.Distance on iPhone6 iOS 8.4 - Unity 5.1

(vector2 - vector2).sqrMagnitude is only about 18% faster then (vector3 - vector3).sqrMagnitude on the same device…

For 10.000.000 loops it took about 0.143 sec for the VectorX.Distance and 0.053 sec for (vector2 - vector2).sqrMagnitude

There is a function that I was referred to which is at least faster on the creator’s machine:

http://blog.alladvanced.net/2011/02/21/square-root-calculation-speed-in-flash-and-unity3d/

which I figured out from a question of mine on the forums here: http://forum.unity3d.com/threads/147661-Square-Root-runs-1000-times-in-0.01ms