Fastest Way to Append Multiple Elements to an Array

Anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 19 14:28:23 PST 2014


On Friday, 19 December 2014 at 18:38:32 UTC, Steven Schveighoffer 
wrote:
> On 12/19/14 12:15 PM, Anonymous wrote:
>> On Friday, 19 December 2014 at 15:25:46 UTC, Steven 
>> Schveighoffer wrote:
>>>
>>> This is surprising to me.
>>>
>>
>> Ho ho ho, this year he has brought your surprise sooner than 
>> expected...
>>
>
> It would be nice if this was the only time this year I was 
> surprised because I didn't fully understand something ;)
>
> -Steve

It's because of this:

On Friday, 19 December 2014 at 14:41:07 UTC, Anonymous wrote:
> 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

argv needs to be a contiguous thing so it's slower to append 
because it's not just storing a reference but the whole thing. 
There is consequently more realloc().
argh is faster because it stores the addresses of the items.

argv appends maybe 33 bytes, 33 bytes and so on.
argh always appens 4 4 4... (32 bits OS) or 8 8 8...(64 bits OS). 
It's faster , always aligned...page-aware.that's all.

Oh Oh oh.


More information about the Digitalmars-d-learn mailing list