- Home /
Optimized Scripting - Variables
Hello everyone, I have a small question in mind. I am writing a sway script for an object, the object's position will be swayed using Mathf.Sin, according to the Vector3 variable that is adjusted through the inspector. I am going to be giving minor examples, but I will expand this script and use it in a lot of places, that's why I am trying to be careful about optimization and asking this question. Now, what grinds my mind is, if I do not want any sway in for example Z axis, I'll leave it 0 right. But if I write the sway script like this :
public Vector3 amount;
transform.position = new Vector3(Mathf.Sin(Time.time) * amount.x, Mathf.Sin(Time.time) * amount.y, Mathf.Sin(Time.time) * amount.z);
This script will try to calculate the sin variable for "0", and I think this may hold some space in the memory or cpu right ? So I thought, I can create variables like this:
float swayX = 0.0f;
if(amount.x != 0)
swayX = Mathf.Sin(Time.time) * amount.x;
and same for the other ones. But I do not know if this kind of checking will cause more overload on the cpu than the first option ?
The other way that I think about is :
private float swayX;
if(amounts.x != 0)
swayX = Mathf.Sin(Time.time) * amount.x;
This one is similar to the second option, but this will also hold a place in the memory for swayX variable, like the second one does.
I do not know if these three options make a difference, eventhough will be used a lot or not, but I still got doubts in my head, and if someone could clear them, it'd be perfect ! Thanks :).
Waste of time to think about optimisation here, really
Indeed, if you need to think about this kind of optimisation you have likely done a lot wrongly, somewhere else.
The way to test this is make a blank project and run the code 10000 times in loop. See which one takes longer.
Answer by Glurth · Mar 06, 2015 at 05:12 PM
Zero is a perfectly valid input for Sin. I don't think checking for Zero will optimize it much.
but you COULD optimize this: (EDIT: This will help, not because I'm multiplying the vector by a float, rather than each component, but because Sin function is called only once)
transform.position = new Vector3(Mathf.Sin(Time.time) * amount.x, Mathf.Sin(Time.time) * amount.y, Mathf.Sin(Time.time) * amount.z);
into
transform.position = new Vector3(amount.x, amount.y, amount.z) *Mathf.Sin(Time.time);
Your answer
![](https://koobas.hobune.stream/wayback/20220613185254im_/https://answers.unity.com/themes/thub/images/avi.jpg)