I used inline functions. It's even worse if he used macros as
the expressions passed are possibly evaluated more than once.
True; however, he did mention the *usual* definition of 'min',
which IME is more often than not as a macro.
It's beyond me what you mean by that. Both times execute
the comparison twice, as a result the select.
Brain fart?
Unsnipped from my previous post:
min3_inefficient(X, Y, Z) becomes
min(X, ((Y < Z)? Y: Z))
((X < ((Y < Z)? Y: Z))? X: ((Y < Z)? Y: Z)))
min3_better(X, Y, Z) becomes
((X < Y)? ((X < Z)? X: Z): (Y < Z)? Y: Z)
Suppose X is the least of the three... then
min3_inefficient compares Y to Z
then compares X to min(Y,Z)
min3_better compares X to Y
then compares X to Z
Suppose Y is the least of the three... then
min3_inefficient compares Y to Z
then compares X to Y
then compares Y to Z
min3_better compares X to Y
then compares Y to Z
Suppose Z is the least of the three... then
min3_inefficient compares Y to Z
then compares X to Z
then compares Y to Z
min3_better compares X to Y
then compares min(X,Y) to Z
See? min3_better makes exactly 2 comparisons in each case,
while min3_inefficient makes 3 comparisons fully 2/3 of the
time, as I said. Thus min3_inefficient *is* less efficient,
because it computes useless comparisons.
You can make
up your own idea of the cost of the flow between the two, but
as I said, it;s negligable. Both functions on the Sun compiler
take the same amount of time.
Try running them more than once.
(But before doing that, take a look at the generated machine
code. I would not be surprised if the GCC folks have optimized
this particular computation, so the Sun folks might have too.)
Templates have no bearing on this situation at all. You could
as easily code this as functions taking doubles without templates
and the answer would be the same.
....except in the case where you wanted to compare pointers.
Or C++ std::strings. Or 'long longs'. Or practically anything
that wasn't a double.
(Which, incidentally, is why the most common implementation of
'min' is as a macro -- because C macros can do things that C
functions can't.)
-Arthur