Cost of .dup vs. instantiation

monarch_dodra via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 29 05:04:34 PDT 2014


On Thursday, 29 May 2014 at 08:49:10 UTC, Chris wrote:
> monarch_dodra:
> Hm. This last point might be an issue. If I process a large 
> input (text in this case) then I might run into trouble with 
> "append" as a class variable. I also had a weird bug, because I 
> didn't clear the memory for overwrite.

You can always implement an "upper bound" approach, where if your 
input data becomes larger than a certain size, you return the 
data directly, and reset your appender. EG:

Appender!(MyType[]) append;
public auto doSomething() {
   scope (failure) { append.clear; }
   // ... do something
   append ~= item;
   MyType[] ret;
   if (append.data.length < 10_000)
   {
     ret = append.data).dup;
     append.clear; //clears buffer, keeps memory.
   }
   else
   {
     ret = append.data;
     append = appender!(MyType[])(); //jettison old appender data.
   }
   return ret;
}


More information about the Digitalmars-d-learn mailing list