Skip to main content

Performance Myth Busters: Variable Allocation

·261 words·2 mins

In Unity Performance Myth Busters I take an assumption and check if it’s still valid or just programming superstition. There is nothing like proof to end an argument or inform a decision. Plus, there is nothing like being humbled by a junior dev because you did not do your homework! Today, I want to chat about local variable usage in an update loop. So, you have all seen a loop like this:

private void Update(){
    Vector3 eularRotation = assetToRotate.localEulerAngles;
    eularRotation.y += Time.smoothDeltaTime * 10f;
    assetToRotate.localEulerAngles = eularRotation;
}

So I created a project to test my theories. I am running on a MacBook Pro, Unity 2017.3.1f1, compiling for Mac standalone. At first, I run it in the editor with the profiler and we are getting the typical GC sawtooth curves. But as we know, profiling in the editor is a lie. Profiling a build, GC is a flat line! No change what so ever. That’s great news but is it only that the change is so tiny, we cant notice? Possible.

Next, I ran 64 instances of my test… and that was a flat line too. Before I bust this myth though, I want to make super sure so we are going to try 100k instances… because I can… and for science. [5 mins later] Yea, that was a little heavy-handed. Let’s try 20k.

So after 20k instances of the above code, I can safely say local variable assignments does not generate garbage. Solid like a rock and myth busssssted!

All my Performance Myth Buster code can be found here https://github.com/collectivemass/UnityPerformanceTests