Does foreach on array literal allocate?
Lionello Lunesu
lionello at lunesu.remove.com
Thu Dec 4 17:53:08 PST 2008
Short answer: yes, they both allocate memory.
Long answer:
_d_arrayliteralT from gc.d is used to create an array:
import std.stdio;
void main()
{
foreach(r; [1, 2, 3])
writefln(r);
asm { nop; }
int a,b,c;
foreach(r; [a, b, c])
writefln(r);
}
__Dmain comdat
assume CS:__Dmain
L0: push EBP
mov EBP,ESP
sub ESP,028h
push 3
push 2
push 1
push 3
push offset FLAT:_D12TypeInfo_G3i6__initZ
call near ptr __d_arrayliteralT
mov -024h[EBP],EAX
mov EAX,-024h[EBP]
lea EAX,0Ch[EAX]
mov -020h[EBP],EAX
add ESP,014h
L27: mov EAX,-024h[EBP]
cmp EAX,-020h[EBP]
jae L4D
mov EAX,-024h[EBP]
mov EAX,[EAX]
mov -01Ch[EBP],EAX
push dword ptr -01Ch[EBP]
push offset FLAT:_D12TypeInfo_B1i6__initZ
call near ptr _D3std5stdio8writeflnFYv
add dword ptr -024h[EBP],4
add ESP,8
jmp short L27
L4D: nop
xor EAX,EAX
mov -018h[EBP],EAX
mov -014h[EBP],EAX
mov -010h[EBP],EAX
push dword ptr -010h[EBP]
push dword ptr -014h[EBP]
push dword ptr -018h[EBP]
push 3
push offset FLAT:_D12TypeInfo_G3i6__initZ
call near ptr __d_arrayliteralT
mov -0Ch[EBP],EAX
mov EAX,-0Ch[EBP]
lea EAX,0Ch[EAX]
mov -8[EBP],EAX
add ESP,014h
L7D: mov EAX,-0Ch[EBP]
cmp EAX,-8[EBP]
jae LA3
mov EAX,-0Ch[EBP]
mov EAX,[EAX]
mov -4[EBP],EAX
push dword ptr -4[EBP]
push offset FLAT:_D12TypeInfo_B1i6__initZ
call near ptr _D3std5stdio8writeflnFYv
add dword ptr -0Ch[EBP],4
add ESP,8
jmp short L7D
LA3: mov ESP,EBP
pop EBP
ret
"Bill Baxter" <wbaxter at gmail.com> wrote in message
news:mailman.92.1228417124.22690.digitalmars-d at puremagic.com...
> Does anyone know off the top of their head if code like this allocates
> or not with current DMD 1.x compilers?
>
> foreach(x; [1, 2, 3, 4])
> {
> // do something non-allocating with x
> }
>
> And is the answer different if the values are only known at runtime? Like
> here:
>
> void a func(int a1, int a2, int a3)
> {
> foreach(x; [a1,a2,a3]) {
> // do something non-allocating with x
> }
>
> }
>
> --bb
More information about the Digitalmars-d
mailing list