Fastest Way to Append Multiple Elements to an Array

zeljkog via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 19 15:24:12 PST 2014


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);
}


More information about the Digitalmars-d-learn mailing list