On Saturday, 4 February 2017 at 16:30:30 UTC, Stefan Koch wrote:
I can present you a nice snippet that just compiled with newCTFE

int[] makeAndInitArray(int until)
{
  int[] result;
  result.length = until;

  foreach(i; 0 .. until)
  {
    result[i] = i;
  }

  return result;
}


int[] filter(alias filterFn)(int[] arr)
{
  int[] result;
  result.length = arr.length;

  uint resultLength;
  foreach(i;0 .. arr.length)
  {
    auto e = arr[i];
    if (filterFn(e))
    {
      result[resultLength++] = e;
    }
  }

  result.length = resultLength;
  // I cannot remember implementing it but shrinking seems to work
  return result;
}
enum arr_500_000 = makeAndInitArray(500_000);

static assert(arr_500_000.filter!(e => !(e % 3)));
static assert([1,2,3,4,5,6,7,8,9,10,11,12,13].filter!(e => !(e % 3)) == [3,6,9,12]);


newCTFE takes a quarter of the time, and only half of the memory.
It would go even faster if we did not create the enum arr_500_000 but instead do that in a function-local variable.

because then the array does not allocate 500_000 expression nodes.


Reply via email to