I recently asked a question about structs, and optimizing some overloaded operators.
Now, I have taken those improvements to heart (or some/most of them), and I return with the following functions (nonmember functions, as I wish for them to be C compliant if possible).
inline Vector2& operator+=(Vector2 &a, const Vector2 &b)
{
a.x += b.x;
a.y += b.y;
return a;
}
inline Vector2 operator+(Vector2 a, const Vector2 &b)
{
a += b;
return a;
}
inline Vector2& operator*=(Vector2 &a, const float &n)
{
a.x *= n;
a.y *= n;
return a;
}
inline Vector2 operator*(Vector2 a, const float &n)
{
a *= n;
return a;
}
inline float operator*(const Vector2 &a, const Vector2 &b)
{
return (a.x * b.x) + (a.y * b.y);
}
inline Vector2 rotate(const Vector2 &a, const float &angle)
{
Vector2 out = a;
out *= cos(angle);
out.x -= sin(angle) * a.y;
out.y += sin(angle) * a.x;
return out;
}
(Please note, I omitted subtraction, and another multiplication operator, as they were equivalent to other operators listed here).
I am currently unable to notice any other potential improvements.
Have I missed anything, that will (potentially) make these functions, as they currently stand, inefficient?
It is pointless to speak of improvements without profiling. However, there could be some room for improvement here:
here, you cache the result of
sin(angle)instead of calling the function twice. But I really have to stress that you should have a profiling system in place before trying any changes, so you can see whether they make a difference or not, and gauge whether any improvements are actually worthwhile. The compiler might well optimize away things that seem to be inefficient when looking at the source code.it is worth knowing about RVO and NRVO, copy ellision and, in C++11, move semantics. Also, see this relevant article.
EDIT: My original answer was badly broken and this one is significantly different.