On Sunday, 4 January 2015 at 01:30:11 UTC, Jonathan Marler wrote:
I've recently looked at how the '==' operator works with classes. I was disappointed to find that 'a == b' always gets rewritten to:

.object.opEquals(a, b);

The reason for my disappointment is that this results in unnecessary overhead. I would think that the compiler would first try to rewrite the '==' operator using a type-specific opEquals method, then fall back on the generic version if one did not exist. Is there a reason for this?

For reference, here is .object.opEquals (according to documentation[1]):

bool opEquals(Object a, Object b)
{
    if (a is b) return true;
    if (a is null || b is null) return false;
    if (typeid(a) == typeid(b)) return a.opEquals(b);
    return a.opEquals(b) && b.opEquals(a);
}

I see one fundamental source of overhead: The types degenerate to Object, resulting in virtual calls that could be avoided. Maybe it'd be worthwhile to templatize object.opEquals: `bool opEquals(A, B)(A a, B b)`.

Also, the typeid thing could be counter-productive with trivial equalities. But it helps with complex ones.

By the way, I think `typeid(a) == typeid(b)` is silly. It calls object.opEquals on the `typeid`s. And if they're not identical, that in turn calls object.opEquals on the `typeid`s of the `typeid`s. That fortunately hits the `is` case, or we'd go on forever. All that only to realize that `typeid(a).opEquals(typeid(b))` suffices.

[1] http://dlang.org/operatoroverloading.html

Reply via email to