-1

It seems to me that for any composite object, it is inefficient to implement operator!= in terms of operator==. For an object with N subobjects to compare, operator== must always perform every one of those comparisons: 2 objects are equal if and only if every sub-object is equal. (Ignoring irrelevant sub-objects for this discussion.)

Compare to operator!=, in which it is sufficient to check sub-objects only until a mismatch is found. To make operator!= delegate to operator== is therefore inefficient in the composite case, as it yields N comparisons in every case, instead of just the worst case.

This is posted as a new question after an overlong comment discussion started by this comment. The other commenter stated:

operator== does not always require N comparisons, it only requires N comparisons in the worst case, which is when at least all but the last subobjects are equal

I can't see how that can possibly be correct..have I missed something?

This is of course far more general than purely C++, but since the discussion was specific to that I've kept the same tag.

Community
  • 1
  • 1
boycy
  • 1,473
  • 12
  • 25
  • 3
    You expect that `operator==` returns `true`. But it can also return `false` and in such a case the first comparison that fails can stop the computation. – Franck Sep 27 '16 at 20:48
  • Note: an implementation like `!(this.a == other.a && this.b == other.b)` will short circut if `this.a != other.a`. https://en.wikipedia.org/wiki/Short-circuit_evaluation (in other words) – Caramiriel Sep 27 '16 at 20:54
  • Short circuit break of comparison depends on probability (neither == or != is better) –  Sep 27 '16 at 20:57
  • I wonder why there are so many downvoters. Seems like a reasonable question to me - even if the OP's arguments don't make too much sense. But there could still be some other reason for prefering one solution over the other. – andreee Oct 01 '18 at 08:56

2 Answers2

6

Both == and != will stop evaluation at the first subobject not satisfying the condition. So, from a general perspective, they are equal.

== will evaluate to:

A==A0 && B==B0 && C==C0 && ....

and stop as soon as A==A0 or B==B0 or C==C0 or .... evaluates false.

!= will evaluate to:

A!=A0 || B!=B0 || C!=C0 || ...

and stop as soon as A!=A0 or B!=B0 or C!=C0 or .... evaluates true.

In specific cases, one may be better than the other but in general they are equal.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
2

Well the same should hold for ==, shouldn't?

As soon as the == operator finds two elements that are not equal it can seize to compare the following elements, since the objects cannot be equal anymore.

JHolub
  • 290
  • 3
  • 15