Andrew Uknown Andrew Uknown - 1 month ago 13
C# Question

Are Unity VectorN variables recalculated?

Unity allows access to vector.magnitude/sqrMagnitude/normalized values through a read only variable and I am unsure if its a c# feature or a unity thing. However I would like to know if I use it multiple times without changing the vector will it recompute the value or return it from the previous computation.

https://docs.unity3d.com/ScriptReference/Vector3.html

Answer

In order to reliably answer this question, one has to look into the bytecode that is executed. In other words, we just open up the UnityEngine.dll in Telerik's decompiler to see what's going on in that class. In my case that file was located at C:\Program Files\Unity\Editor\Data\Managed\UnityEngine.dll.

Here we can see the (partial) contents of the UnityEngine.Vector3 class:

enter image description here enter image description here

You wanted to know about Vector3.magnitude, Vector3.sqrMagnitude and Vector3.normalized. The code for .magnitude is:

    public float magnitude
    {
        get
        {
            return Mathf.Sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
        }
    }

This is a straighforward implementation of a read-only property that computates the magnitude of the vector. As you can see, no caching is done. Let's see sqrMagnitude.

    public float sqrMagnitude
    {
        get
        {
            return this.x * this.x + this.y * this.y + this.z * this.z;
        }
    }

Nope, the same here, no caching involved. However, .normalized is interesting.

    public Vector3 normalized
    {
        get
        {
            return Vector3.Normalize(this);
        }
    }

Which leads us to:

    public static Vector3 Normalize(Vector3 value)
    {
        float single = Vector3.Magnitude(value);
        if (single <= 1E-05f)
        {
            return Vector3.zero;
        }
        return value / single;
    }

The static method Vector3.magnitude is the same as the member-function implementation but with an explicit Vector3 input parameter ofcourse.

So, as you can see from the decompiled bytecode: No caching is done when computing .sqrtMagnitude, .magnitude or .normalized. So, it is in turn wise to only compute these values once and then reuse them if possible, for performance gain.