null Vs [] return arrays
Steven Schveighoffer
schveiguy at yahoo.com
Mon Mar 28 06:24:28 PDT 2011
On Sun, 27 Mar 2011 09:37:47 -0400, bearophile <bearophileHUGS at lycos.com>
wrote:
> I have compiled this little D2 program:
>
>
> int[] foo() {
> return [];
> }
> int[] bar() {
> return null;
> }
> void main() {}
>
>
>
> Using DMD 2.052, dmd -O -release -inline test2.d
>
> This is the asm of the two functions:
>
> _D5test23fooFZAi comdat
> L0: push EAX
> mov EAX,offset FLAT:_D11TypeInfo_Ai6__initZ
> push 0
> push EAX
> call near ptr __d_arrayliteralT
> mov EDX,EAX
> add ESP,8
> pop ECX
> xor EAX,EAX
> ret
>
> _D5test23barFZAi comdat
> xor EAX,EAX
> xor EDX,EDX
> ret
>
> Is this expected and desired? Isn't it better to compile the foo() as
> bar()?
Probably. The runtime that allocates an array looks like this (irrelevant
parts collapsed):
extern (C) void* _d_arrayliteralT(TypeInfo ti, size_t length, ...)
{
auto sizeelem = ti.next.tsize(); // array element size
void* result;
...
if (length == 0 || sizeelem == 0)
result = null;
else
{
...
}
return result;
}
So essentially, you are getting the same thing, but using [] is slower.
-Steve
More information about the Digitalmars-d-learn
mailing list