Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise static arrays in D without a GC allocation?

In D, all array literals are dynamic arrays, and are therefore allocated by the GC.

Even in this simple example:

int[3] a = [10, 20, 30];

The array is heap-allocated and then copied into a.

How are you supposed to initialise a static array without heap-allocation?

You could do it manually:

int[3] a = void;
a[0] = 10;
a[1] = 20;
a[2] = 30;

But this is tedious at best.

Is there a better way?

like image 989
Peter Alexander Avatar asked Jul 19 '11 17:07

Peter Alexander


1 Answers

2017 UPDATE: In any recent version of DMD, using an array initializer on a static array no longer allocates, even if the static array is a local variable (ie stack-allocated).

You can verify this yourself by creating a function where a static array is initialized, and then marking the function as @nogc and observing whether or not it compiles. Example:

import std.random;
import std.stdio;
int[4] testfunc(int num) @nogc
{
    return [0, 1, num, 3];
}

int main()
{
    int[4] arr = testfunc(uniform(0, 15));
    writeln(arr);
    return 0;
}

Since testfunc() compiles despite being @nogc, we know that the array initializer does not allocate.

like image 104
Lewis Avatar answered Sep 20 '22 13:09

Lewis