Fastest Way to Append Multiple Elements to an Array

"Nordlöw" via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 15 12:58:31 PST 2014


On Monday, 15 December 2014 at 15:55:22 UTC, Steven Schveighoffer 
wrote:
>> What's the fastest way to append multiple elements to an 
>> array?:
>
> Before appending, call reserve to avoid the possibility of 
> reallocating multiple times:
>
> arr.reserve(arr.length + n); // about to append n elements.

Thanks!

>
>> Either
>>
>>     arr ~= e1;
>>     arr ~= e2;
>>     arr ~= e3;
>>
>> or
>>
>>     arr ~= [e1,e2,e3];
>
> I wish this would be fastest, but it's not, because this 
> allocates an array on the heap with elements e1, e2, e3 before 
> appending. It would be a superb addition to D if this would 
> simply allocate a stack array (if the array never escapes the 
> expression).

That's what I thought :)


More information about the Digitalmars-d-learn mailing list