I have this question in mind regarding optimazation of compiler when it comes to shorthanded if/else.
I have this function:
double eu_distance (const coor& x, const coor& y) {
return ((y.x - x.x)*(y.x - x.x) + (y.y - x.y)*(y.y - x.y));
}
I am wondering what is more efficient?
min = min > eucl_distance(point_a, point_b) ? eucl_distance(point_a, point_b) : min;
or
double dis = eucl_distance(point_a, point_b);
if (min > dis)
min = dis;
in the former case, does compiler (in my case, GCC 4.6.2) know how to optimize that if/else to keep the return value of eucl_distance() to reuse instead of computing it twice?
A piggy back question would be:
What is more efficient?
(y.x - x.x)*(y.x - x.x)
or
pow((y.x - x.x),2)
PS: Sorry that I cannot pick more than one correct answers!! 🙁 Thank you all for your answers! I really appreciate them!!
There’s no universal answer: you’ll have to profile the code generated
by your implementation to know for sure. In most cases, however, if
eu_distanceis in a separate translation unit, and is not speciallyannotated, the compiler will be unable to know that calling it twice
with the same arguments will give the same results; in this case, the
second form will almost surely be faster. On the other hand, If
eu_distancecan be inlined, any decent optimizer will end upgenerating almost exactly the same code for both.
In practice, I would almost certainly use a third form:
(I am supposing that
eucl_distanceis a typo foreu_distance.)Also, I’d avoid a name like
min. Somebody’s too likely to add ausing namespace std;later, or even to include<windows.h>, withouthvaing defined
NOMINMAX. (<windows.h>definesminandmaxasmacros if
NOMINMAXhas not been defined. Which leads to someinteresting error messages if you define your own
minormax. Oreven include
<algorithm>.)Concerning
pow( x, 2 ): again, you’ll really have to measure, buttypically,
x * xwill be faster, even ifxis a complicatedexpression. (Of course, if the expression is non trivial, then
recognizing that both
xare identical may not be that easy, whichmakes the code harder to read. In such cases, you might want to
consider a small function, say
squared, which does nothing but returnx * x. Inline it if it makes a difference in performance.)