why does clearing an array set its capacity to 0?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Jul 1 16:03:44 PDT 2014
On 07/01/2014 03:51 PM, Vlad Levenfeld wrote:
> Thanks for your replies. The article was quite helpful in clarifying
> some questions I had.
>
> I decided to benchmark the different append methods (with
> ["releaseMode", "inline", "noBoundsCheck", "optimize"]) by appending
> 10,000 elements to arrays with
> ~=,
> Appender,
> with and without first reserving,
> with and without assumeSafeAppend
> and with a custom array type that preallocated an array and kept its
> own length.
>
> The custom array was fastest,
How did you allocate your array? The GC has the APPENDABLE attribute
special for memory blocks that are going to be used as slices:
http://dlang.org/phobos/core_memory.html#.GC.BlkAttr.APPENDABLE
However, if you use your block as a slice, then you might get the same
performance as a slice.
> then the appender was over 2-3x slower,
> and the dynamic array 12-13x slower.
Are you doing bounds checking for your array? Try the -boundscheck=off
compiler flag. (That may be new in 2.066. Otherwise, try -noboundscheck.)
> What surprised me though, was that
> calling reserve didn't actually give much performance improvement. In
> fact, of all the ~= benchmarks, plain dynamic arrays had the best
> performance,
The runtime is very smart about that. As you read in that article, if
there is room at the end of the block, there is almost no cost for
appending more memory to the slice.
> followed by reserved and assumedSafe, followed by reserved.
>
> For the Appender, reserving was negligibly faster.
>
> I'm not sure if I'm doing something wrong but these seem pretty extreme
> to me, as the description of reserve gave me the impression that it was
> roughly the same thing as the custom array (i.e. slicing preallocated
> data).
With a smart growth policy like 50%, the cost of memory allocation is
amortized and negligible. reserve() would bring some benefit but it is
not necessary in most cases. However, when you know the size
before-hand, there is no reason not to take advantage of it either.
Ali
More information about the Digitalmars-d-learn
mailing list