Performance of Vector Addition vs. Component Addition

Hey Unity! The Vector3 is a mutable data type with respect to its components. If you have, say,

Vector3 a = Vector3.up;
Vector3 b = Vector3.right;

You can get the additive resultant as either

return a + b;

or

return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z);

but which one is faster? I’m inclined to think that the internal implementation of the first option is just the second option, and in any case I doubt if the first option can be slower than the second, but the docs for the addition operation don’t specify, and as far as I know it is technically possible that it’s instead implemented

Vector3 operator+(const Vector3& other) {
    this->x += other.x;
    this->y += other.y;
    this->z += other.z;
    return this;
}

which should be faster than the second option since you’re not going out of your way to allocate memory for a brand new Vector3 object.

Here is the implementation of the + operator overload in the Unity engine.

    // Adds two vectors.
    public static Vector3 operator+(Vector3 a, Vector3 b) { return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z); }

The problem with the code you suggest is that one of the two vectors involved in the operation will be irremediably changed. However, when you do 1 + 2, 1 and 2 don’t change, it wouldn’t be logical if it happened with the + operator of the Vector struct.

But, keep in mind that your concerns should not exist. This is micro-optimisation your user will never notice, unless you compute hundreds of vectors each frame.

You might find useful an asset that I made that implements optimizations like the one you posted about. You can find more about the subject here:
https://forum.unity.com/threads/vector3-and-other-structs-optimization-of-operators.477338
The actual asset is : Frame Rate Booster