Empty Array is Null?

Steven Schveighoffer schveiguy at yahoo.com
Wed Mar 19 13:20:24 PDT 2008


"Frits van Bommel" wrote
> Steven Schveighoffer wrote:
>> "Frits van Bommel" wrote
>>> Actually, if you compare an array to null (using 'is') DMD performs an 
>>> 'or' instruction on the .ptr and .length and tests for the flag that it 
>>> sets if the result is zero. This is just an optimization; this is 
>>> equivalent to checking if both .ptr and .length are 0 (though presumably 
>>> faster, since it's a single instruction that doesn't even implement full 
>>> comparison).
>>
>> Huh?  Why does it do that?  If you have a null pointer, then clearly the 
>> length should be 0.  An optimization in my mind would be to just replace 
>> array is null to array.ptr is null.  Is there a good reason to have a 
>> null pointer array with a non-zero length?
>
> Indeed, no program should be able to get a non-empty array with .ptr == 
> null. However, it appears the compiler currently doesn't use that as an 
> optimization opportunity. Maybe even only because Walter didn't think of 
> it, or just because it doesn't really save that much and it isn't worth 
> the trouble of checking if one of the values is known to be null at 
> compile time.
> The 'or' is itself an optimization that only applies when comparing to a 
> 0-length null array, but this optimization may well be implemented 
> completely in the compiler backend which doesn't know that the length 
> should always be null if the pointer is; it may only know that it needs to 
> compare these two numbers against those other two numbers and jump based 
> on the result...

Good point.  I wonder if comparing any struct to null is equivalent to 
comparing if all it's values are 0...

>>>> The sucky part about all this is that if you have an empty array where 
>>>> the pointer is NOT null, then you get a different result (that array is 
>>>> not considered to be null)
>>> Actually, 'array == null' should return true for any empty array. 
>>> Testing arrays with 'is' explicitly requests comparing .ptr and .length 
>>> directly, not paying any attention to the contents; 'is' checks for 
>>> identity, '==' for equivalence.
>>
>> I would guess that the newest D compiler would not allow that, since 
>> comparing to null is now an error except for using 'x is null'
>>
>> Of course, this is another guess, since I haven't downloaded the new 
>> compiler yet :)
>
> I'm pretty sure it's only an error when comparing class instances. It 
> shouldn't be an error to compare pointers or arrays against null. (There's 
> no reason for it to be since they don't use vtables)

I think you are right.  Now that I look at Walter's message, he said 
specifically comparing class to null is invalid...

Thanks

-Steve 




More information about the Digitalmars-d-learn mailing list