Fastest Way to Append Multiple Elements to an Array

MarcelDuchamp via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 19 16:15:20 PST 2014


On Friday, 19 December 2014 at 23:24:13 UTC, zeljkog wrote:
> On 19.12.14 23:56, Ali Çehreli wrote:
>> Can we see the test code please.
>> 
>> Ali
>
> import std.stdio, std.datetime, std.random;
>
> int N = 10_000;
> int len = 1000;
> int k = 4;
>
> struct S{
>    int n1, n2;
> //~ 	this(this){
> //~ 		writeln("this(this)");
> //~ 	}
> }
>
> ref T[] append(T, Args...)(ref T[] arr, auto ref Args args)
> {
>    static if (args.length == 1)
>       return arr ~= args[0];
>    else{
>       arr.length += args.length;
>       foreach(i, ref e; args)
>          arr[$ - args.length + i] = e;
>       return arr;
>    }
> }
>
> void append1(T)(ref T[] arr, T[] args...)
> {
>    arr ~= args;
> }
>
>
> void main() {
>    S[] arr1 = new S[len];
>    S[] arr2, arr3, arr4, arr5;
>    foreach (i; 0..len)
>       arr1[i] = S(uniform(0, 100), uniform(0, 100));
>    auto sw = new StopWatch;
>
>    sw.start();
>    foreach(n; 0..N){
>       for (int i = 0; i < len; i += k){
>          arr2 ~= arr1[i];
>          arr2 ~= arr1[i+1];
>          arr2 ~= arr1[i+2];
>          arr2 ~= arr1[i+3];
> //~ 			arr2 ~= arr1[i+4];
> //~ 			arr2 ~= arr1[i+5];
>       }
>       delete arr2;
>    }
>    sw.stop();
>    long tm = sw.peek.msecs;
>    writeln(tm);
>
>    sw.reset();
>    sw.start();
>    foreach(n; 0..N){
>       for (int i = 0; i < len; i += k){
>          arr3 ~= [arr1[i], arr1[i+1], arr1[i+2], arr1[i+3]/+  , 
> arr1[i+4], arr1[i+5] +/];
>       }
>       delete arr3;
>    }
>    sw.stop();
>    tm = sw.peek.msecs;
>    writeln(tm);
>
>    sw.reset();
>    sw.start();
>    foreach(n; 0..N){
>       for (int i = 0; i < len; i += k){
>          arr4.append(arr1[i], arr1[i+1], arr1[i+2], arr1[i+3]/+
>   , arr1[i+4], arr1[i+5] +/);
>       }
>       delete arr4;
>    }
>    sw.stop();
>    tm = sw.peek.msecs;
>    writeln(tm);
>
>    sw.reset();
>    sw.start();
>    foreach(n; 0..N){
>       for (int i = 0; i < len; i += k){
>          arr5.append1(arr1[i], arr1[i+1], arr1[i+2], 
> arr1[i+3]/+   , arr1[i+4], arr1[i+5] +/);
>       }
>       delete arr5;
>    }
>    sw.stop();
>    tm = sw.peek.msecs;
>    writeln(tm);
> }

You've forget the array of ref version. (append the address of 
the first data)
And adding S to an array is biased. S is fucking only >>8<< 
bytes. add more data to your struct.



More information about the Digitalmars-d-learn mailing list