Reputation: 10284
what are the differences between using these two algorithms. I've always wondered how I should be optimising things.How do they differ memory and speed wise? Is one better than the other? Aside from code clarity I mean.
this is the first version I had:
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);
}
This method is the same, but it doesn't hold any values in variables, it just uses one long calculation
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))));
}
Upvotes: 0
Views: 144
Reputation: 346260
The best you can hope for with the second variant is that the compiler will optimize it to do exactly the same as the first rather than computing the difference vector three times. In either case, the machine will need to store the intermediate results somewhere; it doesn't really matter whether that intermediate storage is a named C++ variable or an anonymous machine language pointer.
And of course this is premature micro-optimization and completely irrelevant compared to the better readability of the first variant.
Upvotes: 0
Reputation: 153909
Do whichever is clearest for you. If there are performance problems,
try the other. Without more exact information concerning the type of
D3DXVECTOR3
and the return value of the operator-
you're using and
any number of other factors, it's impossible to even make a guess as to
which is faster. And until you know that this code is critical, it
doesn't really matter.
Upvotes: 0
Reputation: 70314
Which one is easier to maintain?
I think your first version is easier, since it breaks out the parts and makes the vectorBetween
obvious, as you reuse that a couple of times.
Now, as to which one is faster... a smart compiler will probably figure out how to make both the same speed. Don't worry too much about that until you need to. We are talking about O(1) differences here anyways, so if you do do this in a tight loop, just test both versions. Then you will know which one is faster!
Upvotes: 1
Reputation: 71899
The two algorithms will, under proper optimization options, compile down to exactly the same code. Since the first is far more readable, it is undoubtedly the better of the two.
The correct way to optimize this code is not to get rid of the variables (the compiler can do that for you), but to get rid of the sqrt operation: just compare squared distances.
Upvotes: 5