Re: Testing for equality
Brian Tyler wrote:
I have got into the following habit for overloading the == operator:
class A {
const bool operator==( const A& rhs ) {
return bool( this == &rhs ? true : /* some condition */ );
}
};
I.e. first I check if the variables are actually the same variable, if
not I implement some logic to test for equality of the underlying data
members.
Is this first test a total waste of time (since the number of times I
actually check a variable against itself is probably zero)... hmm,
that pretty much answers my own question, but your opinions would be
appreciated.
It's not a total waste of time if you anticipate people (even yourself)
doing something like
A a;
...
if (a == a)
or
A a;
...
A &b = a;
...
if (a == b)
*a lot* in your code. Even if you can estimate how many times this
might happen, you'd still be better off actually measuring instead of
guessing (or "estimating" for picky folk).
Essentially it comes to this: can some function somewhere in your code
_ever_ compare two objects (referred to by two references) that might
actually be the same object? If it can, and it happens once every ten
thousands of comparisons (often enough?), then you'll be speeding your
comparison up by not doing the actual comparison by about 0.01%. At
the same time, the rest of your comparisons will be slowed down by the
pointer comparison code you've added, and the rate depends on how long
the rest of the comparison takes. It has to be very expensive (more
significantly than comparing pointers) to justify this slowdown. Let
us say that comparing pointers takes 5 CPU ticks. The portion of the
operator == you called "some condition" should then be 50000 CPU ticks
long (or more) to justify wasting 5 ticks to compare pointers just to
save one ten-thousandth occurrance (see the assumption above). To me
it's a simple arithmetic combined with probability.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask