Do equality checks for dynamic arrays attempt to shortcut with pointer comparison
simendsjo
simendsjo at gmail.com
Thu Apr 3 01:28:37 PDT 2014
On 04/03/2014 09:23 AM, dnspies wrote:
> On Thursday, 3 April 2014 at 07:16:53 UTC, simendsjo wrote:
>> On 04/03/2014 09:03 AM, dnspies wrote:
>>> If two dynamic arrays point to the same place in memory, is it fast to
>>> compare them for equality? or does every element still have to be
>>> compared?
>>
>> Equals will first check for memory location.
>> This is from the runtime:
>>
>> bool opEquals(Object lhs, Object rhs)
>> {
>> // If aliased to the same object or both null => equal
>> if (lhs is rhs) return true;
>>
>> // If either is null => non-equal
>> if (lhs is null || rhs is null) return false;
>>
>> // If same exact type => one call to method opEquals
>> if (typeid(lhs) is typeid(rhs) || typeid(lhs).opEquals(typeid(rhs)))
>> return lhs.opEquals(rhs);
>>
>> // General case => symmetric calls to method opEquals
>> return lhs.opEquals(rhs) && rhs.opEquals(lhs);
>> }
>
> But this only applies to objects with a class type. A dynamic array
> isn't an object with a class type, it's a builtin type. Does it use this
> opEquals? Can a dynamic array even be cast to an Object? I don't see
> that "lhs is rhs" will return true since the array startptr-length pairs
> may still occupy different places in memory even if the contents of
> those arrays occupy the same place.
If the arrays have different lengths, they are obviously not equal.
Here's a quick test of the semantics of is on arrays.
auto a = [1, 2];
auto b = a;
assert(a is b);
b = a[0..$];
assert(a is b);
b = a[0..1];
assert(a !is b);
assert(a.ptr == b.ptr);
More information about the Digitalmars-d-learn
mailing list