# 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 :).

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);
``````