I’m currently running an optimization audit on my codebase for my game and noticed Vector3.zero coming up in the profiler. It never really dawned on me that call to that value would have overhead in terms of a constructor and essentially what looks to be a getter in the Deep Profile information.
Here’s my test. I wanted to share it with you guys and get your feedback. It’s not much at first glance, but on my computer it was about 1 second faster to access an instance variable in the class for Vector3.zeo (vZero in the code below) as opposed to Vector3.zero when testing over 5000 iterations of each test against one another, profiler off. It was actually 5 seconds faster with the profiler on, but that’s just miscellaneous information. Even at 1000 iterations, the result was half a second better for the instance.
Just imagine how many places you might end up substituting instances for these convenient, but seemingly not-as-performant vector “getters” out in your code!
using UnityEngine;
using System.Collections;
public class VectorBenchmarks : MonoBehaviour {
Vector3 vZero = Vector3.zero;
Vector3 targetVector;
public int testCount = 5000;
public int currentTest = 0;
// Use this for initialization
void Start () {
StartCoroutine("VectorTest");
}
IEnumerator VectorTest()
{
Debug.Log("Beginning test one, Vector3.zero");
float startTime;
float endTime;
startTime = Time.time;
while(currentTest < testCount ) {
targetVector = Vector3.zero;
++currentTest;
yield return null;
}
endTime = Time.time;
Debug.Log("End Test One: startTime:" + startTime + "endTime:" + endTime + "duration of test:" + (endTime-startTime));
currentTest = 0;
Debug.Log("Beginning test two, instance variable definition of Vector3.zero");
startTime = Time.time;
while(currentTest < testCount ) {
targetVector = vZero;
++currentTest;
yield return null;
}
endTime = Time.time;
Debug.Log("End Test Two: startTime:" + startTime + "endTime:" + endTime + "duration of test:" + (endTime-startTime));
}
}