Premise
I have been seeing a few discussions about the expensiveness of square root functions used in Vector3.Magnitude calculations, and it seems interesting that these are treated as properties of Vector3’s and not functions, because these values take some computational power if done hundreds of times.
As far as I know, Vector3.Magnitude is computed like this:
function GetMagnitude(vector3)
return math.sqrt(
vector3.X*vector3.X +
vector3.Y*vector3.Y +
vector3.Z*vector3.Z
)
end
--alternatively:
function GetMagnitude(vector3)
local sqvec = vector3 * vector3
return math.sqrt(
sqvec.X +
sqvec.Y +
sqvec.Z
)
end
and Vector3.Unit is computed like this:
function GetUnit(vector3)
return vector3 / vector3.Magnitude
end
And that this evaluates to true:
vector3 == vector3.Unit * vector3.Magnitude
Question
- Because of the fact that
.Magnitudeand.Unitare properties, does this mean that those properties are defined when theVector3is created/initialized, or are these properties only defined when they are indexed?
The latter seems more sensible, but could be overlooked. - Are these values cached in the property as well when calculated, if the latter is true?
This also seems sensible, and it probably wouldn’t be overlooked.
Reasons for asking
If you were to use an optimized form of my GetMagnitude function up there without the square root and just squaring the number to compare to make magnitude checks:
function CompareMagnitude(vector3,number)
local magnitude = vector3.X*vector3.X +
vector3.Y*vector3.Y +
vector3.Z*vector3.Z
-- -1 = ">", 0 = "==", 1 = "<"
return math.sign(magnitude - number*number)
end
It might be extra computation for no reason if the magnitude was already calculated, and extra computation for no reason is never a good thing. I might also change a few of my solution responses and change a few people’s opinions if this turns out to be true.