Using closure causes GC allocation

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 4 00:35:25 PDT 2017


On Monday, 4 September 2017 at 05:45:18 UTC, Vino.B wrote:
> On Saturday, 2 September 2017 at 20:54:03 UTC, Vino.B wrote:
>> On Saturday, 2 September 2017 at 20:10:58 UTC, Moritz Maxeiner 
>> wrote:
>>> On Saturday, 2 September 2017 at 18:59:30 UTC, Vino.B wrote:
>>>> [...]
>>>
>>> Cannot reproduce under Linux with dmd 2.076.0 (with commented 
>>> out Windows-only check). I'll try to see what happens on 
>>> Windows once I have a VM setup.
>>>
>>>> [...]
>>>
>>> You changed the type of dFiles, which you return from 
>>> cleanFiles, without changing the return type of cleanFiles. 
>>> Change the return type of cleanFiles to the type the compiler 
>>> error above tells you it should be (`Tuple!(string, 
>>> string)[]` instead of `string[][]`), or let the compiler 
>>> infer it via auto (`auto cleanFiles(...`).
>>
>> Hi,
>>
>>  Thank you very much, was able to resolve the second code 
>> issue by changing the return type of the function.
>
> Hi,
>
>   In order to resolve the issue "Using closure causes GC 
> allocation" it was stated that we need to use delegates, can 
> you please help me on how to as i have not gone that much far 
> in D programming.
>
> import std.stdio: File,writeln;
> import std.datetime.systime: Clock, days, SysTime;
> import std.file: SpanMode, dirEntries, exists, isFile, mkdir, 
> remove;
> import std.typecons: tuple, Tuple;
> import std.algorithm:  filter, map, each;
> import std.array: array;
>
> Tuple!(string)[] logClean (string[] Lglst, int LogAge) {
> 	if (!Lglst[0].exists) { mkdir(Lglst[0]); }
> 	auto ct1 = Clock.currTime();
> 	auto st1 = ct1 + days(-LogAge);
> 	auto dFiles = dirEntries(Lglst[0], SpanMode.shallow).filter!(a 
> => a.exists && a.isFile && a.timeCreated < st1).map!(a => 
> tuple(a.name)).array;
> 	dFiles.each!(a => a[0].remove);
> 	return dFiles;
> }
>
> void main () {
> string[] LogDir = 
> ["C:\\Users\\bheev1\\Desktop\\Current\\Script\\D\\Logs"];
> int  LogAge = 1;
> logClean(LogDir,LogAge);
> }
>
> From,
> Vino.B

If you are getting Using closure causes GC allocation from the 
above, it will be because you reference a local in the template 
delegate argument to filter:

filter!(a => a.exists &&
         a.isFile &&
         a.timeCreated < st1)
                        ^^^
because of the local (st1) it needs a closure. I can't remember 
how to transform delegates to take parameters and then call with 
the parameter set to the local, someone else will have to fill 
you in on that one.


More information about the Digitalmars-d-learn mailing list