null Vs [] return arrays

Steven Schveighoffer schveiguy at yahoo.com
Fri Apr 1 05:38:45 PDT 2011


On Fri, 01 Apr 2011 06:38:56 -0400, Regan Heath <regan at netmail.co.nz>  
wrote:

> On Mon, 28 Mar 2011 17:54:29 +0100, bearophile  
> <bearophileHUGS at lycps.com> wrote:
>> Steven Schveighoffer:
>>
>>> So essentially, you are getting the same thing, but using [] is slower.
>>
>> It seems I was right then, thank you and Kagamin for the answers.
>
> This may be slightly OT but I just wanted to raise the point that  
> conceptually it's nice to be able to express (exists but is empty) and  
> (does not exist).  Pointers/references have null as a (does not exist)  
> "value" and this is incredibly useful.  Try doing the same thing with  
> 'int' .. it requires you either use int* or pass an additional boolean  
> to indicate existence.. yuck.
>
> I'd suggest if someone types '[]' they mean (exists but is empty) and if  
> they type 'null' they mean (does not exist) and they may be relying on  
> the .ptr value to differentiate these cases, which is useful.  If you're  
> not interested in the difference, and you need performance, you simply  
> use 'null'.  Everybody is happy. :)

The distinction is useful if you have something to reference (e.g. an  
empty slice that points at the end of a pre-existing non-empty array).   
But [] is a new array, no point in allocating memory just so the pointer  
can be non-null.  Can you come up with a use case to show why you'd want  
such a thing?

Your plan would mean that [] is a memory allocation.  I'd rather not have  
the runtime do the lower performing thing unless there is a good reason.

As an alternative, you could use (cast(T *)null)[1..1] if you really  
needed it (this also would be higher performing, BTW since the runtime  
array literal function would not be called).

-Steve


More information about the Digitalmars-d-learn mailing list