Fastest Way to Append Multiple Elements to an Array

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 18 05:50:08 PST 2014


On 12/17/14 6:15 AM, zeljkog wrote:
> On 15.12.14 01:00, "Nordlöw" wrote:
>> Isn't this algorithm already encoded somewhere in Phobos?
>
> void append(T, Args...)(ref T[] arr, auto ref Args args){
> {
>     static if (args.length == 1)
>        arr ~= args[0];     // inlined
>     else{
>        arr.length += args.length;
>        foreach(i, e; args)
>           arr[$ - args.length + i] = e;
>     }
> }
>
> I've just tested, this looks usable.
> Equal for 1 item, considerably (~40%) faster for 2, and much (100+%) faster for more.
> Also more convenient.

This makes sense. The cost of calling a function is much much higher 
than copying a single element.

> Maybe samthing like that should go to Fobos.

Definitely. I would love to see the improvement, however, of having arr 
~= [a, b, c] do this automatically by the compiler.

I wonder how your code compares to this:

void append(T)(ref T[] arr, T[] args...)
{
    arr ~= args;
}

Which is how I would have approached it. Your solution is more general, 
but mine has the benefit of avoiding the double-initialization of the data.

-Steve


More information about the Digitalmars-d-learn mailing list