Fastest Way to Append Multiple Elements to an Array

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 15 03:31:20 PST 2014


On Sunday, 14 December 2014 at 23:16:12 UTC, Nordlöw wrote:
> What's the fastest way to append multiple elements to an array?:
>
> Either
>
>     arr ~= e1;
>     arr ~= e2;
>     arr ~= e3;
>
> or
>
>     arr ~= [e1,e2,e3];
>
> or some other trick?

It does somewhat depend on context but std.array.appender is 
generally a good choice. It supports appending elements 
individually, appending a range of elements and manually 
reserving extra space.

E.g.

auto app = appender(somePreExistingArray);
app ~= e0;
app ~= [e1, e2];
app.reserve(3); //eagerly ensures that there's 3 elements 
capacity,
//guaranteeing at most one re-allocation for adding the following 
3 elements
app ~= e3;
app ~= e4;
app ~= e5;

or my personal favourite:

app ~= only(e6, e7, e8, e9);

When you append a range to an appender it will use the length of 
the range (if available) to reserve space ahead-of-time.

There is a (small) cost to creating an appender, so you ideally 
don't want to make a new one every time you add a couple of 
elements (this isn't a deficiency in appender, it's just how GC 
slices are in D).


More information about the Digitalmars-d-learn mailing list