Fastest Way to Append Multiple Elements to an Array

Anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 19 06:41:06 PST 2014


On Thursday, 18 December 2014 at 22:27:06 UTC, zeljkog wrote:
> On 18.12.14 14:50, Steven Schveighoffer wrote:
>> I wonder how your code compares to this:
>> 
>> void append(T)(ref T[] arr, T[] args...)
>> {
>>     arr ~= args;
>> }
>
> This is ~20% slower for ints, but it difference  increases for 
> bigger structs.

What a big surprise. If you make an array of struct, each item of 
your array has the length of the struct. structs a values.
If you want to append a struct to an array just append a pointer 
to the struct:

----------
struct arg{uint a,r,g,h;};

arg * [] argh;
arg [] argv;

foreach(immutable i; 0..1000)
   argh ~= new arg;
----------

so in argh, each item is a size_t pointer. damn.
In argv, the delta between each item is 
(a.sizeof+r.sizeof+g.sizeof+h.sizeof)
In argh, the delta between each item is (arg *).sizeof



More information about the Digitalmars-d-learn mailing list