我剛剛得知編譯器巧妙地將函數和變量的調用替換爲它們所代表的代碼。考慮到這一點,第二種方法事實上會比以下更好(由於清晰度),實際上運行速度與第一種方法一樣快?編譯器優化
//check to see if sphere intersects the box
bool BoundingBox::Intersects(BoundingSphere boundingSphere)
{
// check for intersection on each axis by seeing if the radius is large enough to reach the edge of the cube on the
// appropriate side. All must evaluate to true for there to be an intersection.
return (
((boundingSphere.Centre().x < negCorner.x && boundingSphere.Radius() > posCorner.x - boundingSphere.Centre().x) ||
(boundingSphere.Centre().x > posCorner.x && boundingSphere.Radius() > boundingSphere.Centre().x - negCorner.x))
&&
((boundingSphere.Centre().y < negCorner.y && boundingSphere.Radius() > posCorner.y - boundingSphere.Centre().y) ||
(boundingSphere.Centre().y > posCorner.y && boundingSphere.Radius() > boundingSphere.Centre().y - negCorner.y))
&&
((boundingSphere.Centre().z < negCorner.z && boundingSphere.Radius() > posCorner.z - boundingSphere.Centre().z) ||
(boundingSphere.Centre().z > posCorner.z && boundingSphere.Radius() > boundingSphere.Centre().z - negCorner.z)));
}
第二種方法:
//check to see if sphere intersects the box
bool BoundingBox::Intersects(BoundingSphere boundingSphere)
{
bool xIntersects, yIntersect, zIntersects;
xIntersects =
((boundingSphere.Centre().x < negCorner.x && boundingSphere.Radius() > posCorner.x - boundingSphere.Centre().x) ||
(boundingSphere.Centre().x > posCorner.x && boundingSphere.Radius() > boundingSphere.Centre().x - negCorner.x)));
yIntersects =
((boundingSphere.Centre().y < negCorner.y && boundingSphere.Radius() > posCorner.y - boundingSphere.Centre().y) ||
(boundingSphere.Centre().y > posCorner.y && boundingSphere.Radius() > boundingSphere.Centre().y - negCorner.y)));
zIntersects =
((boundingSphere.Centre().z < negCorner.z && boundingSphere.Radius() > posCorner.z - boundingSphere.Centre().z) ||
(boundingSphere.Centre().z > posCorner.z && boundingSphere.Radius() > boundingSphere.Centre().z - negCorner.z)));
return (xIntersects && yIntersects && zIntersects);
}
也許這不是最好的例子,因爲它們都比較相似,但是想法是第二個更清晰但使用更多線條。 – SirYakalot
在某種程度上取決於你使用的編譯器以及它如何優化代碼:) – Eilidh
這更多的是關於可讀性和優化。 – Philip