Behaviour of append (~=)

Lionello Lunesu lio at lunesu.remove.com
Tue May 30 06:42:26 PDT 2006


Daniel Keep wrote:
> 
> Lionello Lunesu wrote:
>> Why does the appending to a 'null' array cause the contents to be copied?
>>
>> int[] ar1; // some array, not constant
>>
>> int[] ar2 = null;
>> ar2 ~= ar1;
>> // ar2 !is ar1
>>
>> But it could be like this:
>> if (ar2)
>>   ar2 ~= ar1;
>> else
>>   ar2 = ar1;
>>
>> Wouldn't it be a good optimization for ~= to check for null first, to
>> prevent the copy?
>>
>> L.
> 
> I think the problem with this is that it's an edge case.  With your
> suggestion, appending to a null array and appending to an *empty* array
> would have completely different semantics.  Now, every programmer who
> uses arrays has to watch out for this one special case.

It doesn't have to be different. It only depends on what the compiler's 
testing. If it tests "ar2.length" then the two cases will be treated the 
same was (no copy).

> Yes, it would be better performance-wise, but it would be hell on
> programmers since it's non-obvious behaviour.

I don't think those programmers should write code that depends on the 
compiler copying the data in those cases. You got the array you asked 
for, so? If you want to make sure have a copy, you probably needed to 
.dup yourself anyway.

L.



More information about the Digitalmars-d-learn mailing list