我最近问了一个有关结构的问题,并优化了一些重载运算符。
现在,我已经将这些改进(或其中的一些/大部分)牢记在心,并且我返回了以下函数(非成员函数,因为我希望它们尽可能兼容 C)。
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;
}
(请注意,我省略了减法和另一个乘法运算符,因为它们与此处列出的其他运算符等效)。
我目前无法注意到任何其他潜在的改进。 我是否错过了任何可能(可能)使这些功能(按照目前的情况)变得低效的事情?
最佳答案
不进行分析就谈论改进是没有意义的。但是,这里可能还有一些改进的空间:
inline Vector2 rotate(const Vector2& a, const float &angle) {
Vector2 out = a;
out *= cos(angle);
const float sinA + sin(angle);
out.x -= sinA * a.y;
out.y += sinA * a.x;
return out;
}
在这里,您可以缓存 sin(angle)
的结果,而不是调用该函数两次。但我真的必须强调,在尝试任何更改之前,您应该有一个分析系统,这样您就可以看到它们是否有所作为,并衡量任何改进是否真正值得。编译器很可能会优化掉那些在查看源代码时看起来效率低下的东西。
值得了解RVO and NRVO , copy ellision并且,在 C++11 中,move semantics 。另请参阅此 relevant article .
编辑:我原来的答案被严重破坏,这个答案有很大不同。
关于c++ - Vector2 运算符改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10680236/