变量与长算法

Sir*_*lot 0 c++ performance

使用这两种算法有什么区别.我一直想知道我应该如何优化它们.他们如何区分内存和速度?这个比那个好吗?除了代码清晰度,我的意思是.

这是我的第一个版本:

bool Intersects(BoundingSphere boundingSphere)
{
    D3DXVECTOR3 vectorBetween = (centre - boundingSphere.centre);

    // works out the distance between the sphere centre's using pythag
    float distance = sqrt(
                         pow(vectorBetween.x, 2) 
                       + pow(vectorBetween.y, 2) 
                       + pow(vectorBetween.z, 2));

    // if two radius's add to more than the distance between the centres
    return (radius + boundingSphere.radius > distance);
}
Run Code Online (Sandbox Code Playgroud)

这个方法是相同的,但它不包含变量中的任何值,它只使用一个长计算

bool Intersects(BoundingSphere boundingSphere)
{
    return (radius + boundingSphere.radius >
            (sqrt(pow((centre - boundingSphere.centre).x, 2) +
                  pow((centre - boundingSphere.centre).y, 2) +
                  pow((centre - boundingSphere.centre).z, 2))));
}
Run Code Online (Sandbox Code Playgroud)

Seb*_*edl 5

在适当的优化选项下,这两种算法将编译为完全相同的代码.由于第一个更具可读性,因此无疑是两者中较好的一个.

优化此代码的正确方法不是摆脱变量(编译器可以为您做到这一点),而是摆脱sqrt操作:只是比较平方距离.

  • @Sir:因为如果`sqrt(x1*x1 + y1*y1)> sqrt(x2*x2 + y2*y2)`那么`(x1*x1 + y1*y1)>(x2*x2 + y2*y2)` .`sqrt`是单调的. (2认同)
  • @SirYakalot:只要你使用乘法而不是`pow`,平方几乎肯定比取平方根更快. (2认同)