I did a lot of research on the topic of performance optimization in Unity. I recently added all of them up and compared the results to decide whether they are worth it or not. Obviously, there is no such thing as too much performance but with having clean, pretty code in the back of your mind, you have to evaluate and see to which extent code optimization is worth it. You’ll grasp the full meaning of this if you continue reading.
1.) Minimize Vector Math
Let’s say you are calculating a Vector3 velocity by a float speed and Time.deltaTime. If you do it like this:
Vector3 newVelocity = velocity * speed * Time.deltaTime;
Under the hood of Unity, this does actually make two vector multiplications.
But if you then just combine all the floats together first by simply placing parenthesis Unity only will do one vector multiplication.
You could go even further with that and optimize it even more by doing it like this:
float factor = speed * time;
newVelocity.x = velocity.x * factor;
newVelocity.y = velocity.y * factor;
newVelocity.z = velocity.z * factor;
Now you will start to understand what I meant by making compromises regarding clean coding. Obviously, this doesn’t look as bad in a simple code with a few lines, but it will be way harder to read on a longer project.
2.) Reducing Engine Calls
Unity is written in unmanaged C++ code, while we are working with managed C# code – so everytime we request something from Unity the engine has to process a lot of data to go on the one type of code to another.
Let’s say you need an object’s transform, by calling gameObject.transform, Unity does some safety checks before returning, for example checking if the object does exist. You can avoid these checks if you cache the objects Transform. Obviously, this is only a good idea if you are sure that the object can’t be deleted.
Another thing that would be a good idea to do in this regard is instead of using Time.deltaTime creating a globalDeltaTime and using this instead.
Or, if you are sure that an object’s position isn’t going to be touched by anything else but your script you can simple cache your lastPosition yourself and update it if you move the object.
3.) Set Position and Rotation at the same time
This is only possible if you are using Unity 5.6 as this was a hidden function in earlier versions that could only be activated if you had access to the Unity Engine Source Code. This function is very useful if you have to change position and rotation of an object as it allows you to do both things at half the price.
Deep Profiling Results:
Now I know this is rather theoretical and you possibly heard some of those tips before but I actually went ahead and tested it out in a scene with 1000 active objects that had the following very unoptimized script attached.
And here is the deep profiling of exactly that scene and the performance output in the game view:
And the test results under exactly the same circumstances: