GC allocation

QAston via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Apr 21 08:44:56 PDT 2016


On Thursday, 21 April 2016 at 15:22:15 UTC, Alex wrote:
> Hi all!
> timing my program with valgrind/cachegrind and using -vgc 
> option of the compiler found the message:
> "using closure causes GC allocation"
>
> The question is:
> does the usage of the closure causes the GC allocation on every 
> usage of the closure or only on creation/assigning of it? If 
> the former, why?
>
> I'm not sure, if the context of my problem (say: context of the 
> closure) is relevant, but have some thoughts about and a 
> working implementation of it, so if any information is needed, 
> just give me a sign.
>
> Thanks in advance :)

Closure (delegate type) objects have to allocate because they're 
reference types and have state. For stateful reference types to 
be safe they have to be put on the GC allocated heap.

In other words - closures work just like classes. The allocation 
is done for each instance of closure you create and stores the 
variables you captured from the stack. When you don't capture you 
can use plain functions which don't use GC.

See also:
https://dlang.org/spec/function.html#closures


More information about the Digitalmars-d-learn mailing list