Answers to Are Unity VectorN variables recalculated? ( 1 )

  1. 2016-11-01 17:11

    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.

Leave a reply to - Are Unity VectorN variables recalculated?

◀ Go back