Cost of .dup vs. instantiation
monarch_dodra via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed May 28 10:33:17 PDT 2014
On Wednesday, 28 May 2014 at 14:36:25 UTC, Chris wrote:
> I use Appender to fill an array. The Appender is a class
> variable and is not instantiated with each function call to
> save instantiation. However, the return value or the function
> must be dup'ed, like so:
>
> Appender!(MyType[]) append;
> public auto doSomething() {
> scope (exit) { // clear append }
> // ... do something
> append ~= item;
> return (append.data).dup
> }
>
> My question is whether I save anything with Appender as a class
> variable here. I have to .dup the return value (+ clear the
> Appender). If I had a new Appender with each function call, it
> might be just as good.
>
> public auto doSomething() {
> Appender!(MyType[]) append;
> // ....
> return append.data.
> }
>
> Right or wrong?
You might save a little because you avoid the cost of "growing"
your appender repeatedly: Once the appender has come to
"maturity", it will very likely stop growing.
At that point, you only pay for *1* allocation per call to
doSomething. Further advantages include:
- dup has "APPENDABLE" info (whereas appender.data does not).
- less wasted memory: dup uses no more memory than it has to,
whereas Appender may over-allocate, depending on how you fill it.
The "downside" to your approach is that you keep a handle on a
buffer that can grow, but never shrink. If a at a certain point,
you have to process some particularly large input, then you'll
consume excessive amounts of memory.
More information about the Digitalmars-d-learn
mailing list