Are magnitude checks really that expensive?

Hi, I’m making an octree and I’m on the border right now between going for an AABB check or just a magnitude check. But, I’ve been told that magnitude checks are more expensive because they use square roots. So, are magnitude checks really that expensive and should I go for the AABB check for the extra performance, or does it really not matter whichever one I choose?

thanks, ninjamaster5355

I really doubt magnitude checks are gonna impact your performances if used on a moderate scale.

Unless you do notice differences, you should be safe to go.

3 Likes

Square roots are inherently slow when you are comparing them to way simpler alternatives

Also for fun I benchmarked the magnitude method and compared it to calculating the displacement manually

Note that math.sqrt() is around the same performance as ()^0.5

3 Likes

Figuring out which of a dozen players is closest to a point → magnitude is fine

Figuring out which of a thousand parts is closest to a point → maybe consider a more complicated structure—if you’ve measured it and determined it’s slow (and measured it after and determined it’s faster)

1 Like

Thanks for the detailed answer and everyone else for answering! :smile:
Since there’s not much of a difference between them I think I’ll just go with an AABB check since I’ve pretty much started working on one.

I’m not sure what the exact performance cost of using square roots is but the use of them isn’t necessary when doing distance checks. For example, the following snippets are equivalent to the other:

local distance = math.sqrt(x^2 + y^2 + z^2)
local desired_distance = 100

print(distance < desired_distance)
local distance = x^2 + y^2 + z^2
local desired_distance = 100^2

print(distance < desired_distance)
3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.