Vectors are structs and therefore don’t generate garbage, unless you explicitly box them in some manner.
Vector3’s are C#/.Net structs, and therefore are not actually performed on the C++ side of the engine.
Here is the source for the Vector3 addition operator (decompiled for UnityEngine.dll):
public static Vector3 operator +(Vector3 a, Vector3 b)
{
return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
Effectively when you say:
v1 = v2 + v3;
You’re really saying:
v1 = Vector3.Add(v2, v3);
So, the addition operator method is loaded up onto the stack, copies of v2 and v3 are passed in. This method then calls the struct constructor passing the in the sum of each vector component, this will technically allocate yet another method onto the stack to then set the fields of said struct (as for the mono runtime optimizing struct constructors… we’re not going to get into all that). Finally that new Vector3 is returned and set to v1.
For optimizations sake it is technically most efficient to inline addition as:
v1.x = v2.x + v3.x;
v1.y = v2.y + v3.y;
v1.z = v2.z + v3.z;
Though if you’re seeing performance issues at this level of things… you got bigger problems.
The only places I would say you should inline vector addition is if you have some loop where you have to sum thousands of vectors. For example this:
Vector3[] arr = *An array of thousands of Vectors*;
Vector3 result = Vector3.zero;
for(int i = 0; i < arr.Length; i++)
{
result += arr[i];
}
vs
Vector3[] arr = *An array of thousands of Vectors*;
Vector3 result = Vector3.zero;
for(int i = 0; i < arr.Length; i++)
{
result.x += arr[i].x;
result.y += arr[i].y;
result.z += arr[i].z;
}
Which honestly though the difference still isn’t much. On my machine we’re talking a difference of 4ms vs 1.5ms for an array of 100,000 vectors. Which again… you have bigger issues here than the addition operator. Why are you looping and summing 100,000 vectors in an array? Maybe this expensive job should be threaded, rather than optimized via the operator.
With that said… Unity’s implementation of the addition operator uselessly requires 2 stack layers. It would technically been better for them to say:
public static Vector3 operator +(Vector3 a, Vector3 b)
{
a.x += b.x;
a.y += b.y;
a.z += b.z;
return a;
}
But eh, who am I to complain.