Let's get the semantic around closure fixed.

Steven Schveighoffer schveiguy at gmail.com
Wed May 19 19:48:52 UTC 2021


On 5/19/21 3:29 PM, Adam D. Ruppe wrote:
> On Wednesday, 19 May 2021 at 19:01:59 UTC, Walter Bright wrote:
>> Having a hidden allocation per loop will be completely unexpected for 
>> such a simple looking loop for a lot of people. That includes pretty 
>> much all of *us*, too.
> 
> Citation needed.
> 
> It is fairly well known that closures and objects are pretty 
> interchangeable, so the allocation should surprise nobody. This is a 
> very common pattern in several languages. And even ones that don't do 
> this have workarounds - a function returning a function that gets called 
> to capture the arguments (this works in D as well btw) - since the 
> allocation is kinda the point of a closure.


e.g.:

foreach(i; someLargeThing)
{
    if(Clock.currTime.year == 2020)// i.e. never
      dg = {return  i;};
}

If we defensively allocate for the delegate, this is going to allocate 
every iteration of someLargeThing, even though it's very rare that it 
will need to.

> 
> Whereas the current behavior surprises most everybody AND is pretty 
> useless.

Nobody disagrees. What the disagreement here is, whether we should make 
the behavior work as expected at all costs, or invalidate the behavior 
completely because it's too costly.

-Steve


More information about the Digitalmars-d mailing list