D also provides the mechanisms to write code where the garbage collector is not involved. More information is provided below.
Programmers accustomed to explicitly managing memory allocation and deallocation will likely be skeptical of the benefits and efficacy of garbage collection. Experience both with new projects written with garbage collection in mind, and converting existing projects to garbage collection shows that:
Garbage collection is not a panacea. There are some downsides:
These constraints are addressed by techniques outlined in Memory Management, including the mechanisms provided by D to control allocations outside the GC heap.
There is currently work in progress to make the runtime library free of GC heap allocations, to allow its use in scenarios where the use of GC infrastructure is not possible.
The GC works by:
The garbage collector looks for roots in:
If the only pointer to an object is held outside of these areas, then the collector will miss it and free the memory.
To avoid this from happening, either
Pointers in D can be broadly divided into two categories: Those that point to garbage collected memory, and those that do not. Examples of the latter are pointers created by calls to C's malloc(), pointers received from C library routines, pointers to static data, pointers to objects on the stack, etc. For those pointers, anything that is legal in C can be done with them.
For garbage collected pointers and references, however, there are some restrictions. These restrictions are minor, but they are intended to enable the maximum flexibility in garbage collector design.
void* p; ... int x = cast(int)p; // error: undefined behavior
The garbage collector does not scan non-pointer fields for GC pointers.
p = cast(void*)(cast(int)p | 1); // error: undefined behavior
p = cast(void*)12345678; // error: undefined behavior
A copying garbage collector may change this value.
if (p1 < p2) // error: undefined behavior ...
since, again, the garbage collector can move objects around in memory.
char* p = new char[10]; char* q = p + 6; // ok q = p + 11; // error: undefined behavior q = p - 1; // error: undefined behavior
struct Foo { align (1): byte b; char* p; // misaligned pointer }
Misaligned pointers may be used if the underlying hardware supports them and the pointer is never used to point into the GC heap.
Things that are reliable and can be done:
union U { void* ptr; int value }
char[] p = new char[10]; char[] q = p[3..6]; // q is enough to hold on to the object, don't need to keep // p as well.
One can avoid using pointers anyway for most tasks. D provides features rendering most explicit pointer uses obsolete, such as reference objects, dynamic arrays, and garbage collection. Pointers are provided in order to interface successfully with C APIs and for some low level work.
Garbage collection doesn't solve every memory deallocation problem. For example, if a pointer to a large data structure is kept, the garbage collector cannot reclaim it, even if it is never referred to again. To eliminate this problem, it is good practice to set a reference or pointer to an object to null when no longer needed.
This advice applies only to static references or references embedded inside other objects. There is not much point for such stored on the stack to be nulled because new stack frames are initialized anyway.
Although D does not currently use a moving garbage collector, by following the rules listed above one can be implemented. No special action is required to pin objects. A moving collector will only move objects for which there are no ambiguous references, and for which it can update those references. All other objects will be automatically pinned.
Some sections of code may need to avoid using the garbage collector. The following constructs may allocate memory using the garbage collector:
Since version 2.067, The garbage collector can now be configured through the command line, the environment or by options embedded into the executable.
By default, GC options can only be passed on the command line of the program to run, e.g.
app "--DRT-gcopt=profile:1 minPoolSize:16" arguments to app
Available GC options are:
In addition, --DRT-gcopt=help will show the list of options and their current settings.
Command line options starting with "--DRT-" are filtered out before calling main, so the program will not see them. They are still available via rt_args.
Configuration via the command line can be disabled by declaring a variable for the linker to pick up before using its default from the runtime:
extern(C) __gshared bool rt_cmdline_enabled = false;
Likewise, declare a boolean rt_envvars_enabled to enable configuration via the environment variable DRT_GCOPT:
extern(C) __gshared bool rt_envvars_enabled = true;
Setting default configuration properties in the executable can be done by specifying an array of options named rt_options:
extern(C) __gshared string[] rt_options = [ "gcopt=initReserve:100 profile:1" ];
Evaluation order of options is rt_options, then environment variables, then command line arguments, i.e. if command line arguments are not disabled, they can override options specified through the environment or embedded in the executable.
Selecting precise as the garbage collector via the options above means type information will be used to identify actual or possible pointers or references within heap allocated data objects. Non-pointer data will not be interpreted as a reference to other memory as a "false pointer". The collector has to make pessimistic assumptions if a memory slot can contain both a pointer or an integer value, it will still be scanned (e.g. in a union).
To use the GC memory functions from core.memory for data with a mixture of pointers and non-pointer data, pass the TypeInfo of the allocated struct, class, or type as the optional parameter. The default null is interpreted as memory that might contain pointers everywhere.
struct S { size_t hash; Data* data; } S* s = cast(S*)GC.malloc(S.sizeof, 0, typeid(S));
Attention: Enabling precise scanning needs slightly more caution with type declarations. For example, when reserving a buffer as part of a struct and later emplacing an object instance with references to other allocations into this memory, do not use basic integer types to reserve the space. Doing so will cause the garbage collector not to detect the references. Instead, use an array type that will scan this area conservatively. Using void* is usually the best option as it also ensures proper alignment for pointers being scanned by the GC.
Windows only: As of version 2.075, the DATA (global shared data) and TLS segment (thread local data) of an executable or DLL can be configured to be scanned precisely by the garbage collector instead of conservatively. This takes advantage of information emitted by the compiler to identify possible mutable pointers inside these segments. Immutable pointers with initializers are excluded from scanning, too, as they can only point to preallocated memory.
Precise scanning can be enabled with the D runtime option "scanDataSeg". Possible option values are "conservative" (default) and "precise". As with the GC options, it can be specified on the command line, in the environment or embedded into the executable, e.g.
extern(C) __gshared string[] rt_options = [ "scanDataSeg=precise" ];
Attention: Enabling precise scanning needs slightly more caution typing global memory. For example, to pre-allocate memory in the DATA/TLS segment and later emplace an object instance with references to other allocations into this memory, do not use basic integer types to reserve the space. Doing so will cause the garbage collector not to detect the references. Instead, use an array type that will scan this area conservatively. Using void* is usually the best option as it also ensures proper alignment for pointers being scanned by the GC.
class Singleton { void[] mem; } align(__traits(classInstanceAlignment, Singleton)) void*[(__traits(classInstanceSize, Singleton) - 1) / (void*).sizeof + 1] singleton_store; static this() { emplace!Singleton(singleton_store).mem = allocateMem(); } Singleton singleton() { return cast(Singleton)singleton_store.ptr; }
For precise typing of that area, let the compiler generate the class instance into the DATA segment:
class Singleton { void[] mem; } shared(Singleton) singleton = new Singleton; shared static this() { singleton.mem = allocateSharedMem(); }
This doesn't work for TLS memory, though.
By default the garbage collector uses all available CPU cores to mark the heap.
This might affect your application if it has threads that are not suspended during the mark phase of the collection. Configure the number of additional threads used for marking by GC option parallel, e.g. by passing --DRT-gcopt=parallel:2 on the command line or embedding the option into the binary via rt_options. The number of threads actually created is limited to core.cpuid.threadsPerCPU-1. A value of 0 disables parallel marking completely.
GC implementations are added to a registry that allows to supply more implementations by just linking them into the binary. To do so add a function that is executed before the D runtime initialization using pragma(crt_constructor):
import core.gc.gcinterface, core.gc.registry; extern (C) pragma(crt_constructor) void registerMyGC() { registerGCFactory("mygc", &createMyGC); } GC createMyGC() { __gshared instance = new MyGC; instance.initialize(); return instance; } class MyGC : GC { /*...*/ }
[The GC modules defining the interface (gc.interface) and registration (gc.registry) are currently not public and are subject to change from version to version. Add an import search path to the druntime/src path to compile the example.]
The new GC is added to the list of available garbage collectors that can be selected via the usual configuration options, e.g. by embedding rt_options into the binary:
extern (C) __gshared string[] rt_options = ["gcopt=gc:mygc"];
The standard GC implementation from a statically linked binary can be removed by redefining the function extern(C) void* register_default_gcs(). If no custom garbage collector has been registered all attempts to allocate GC managed memory will terminate the application with an appropriate message.
unittest, Unit Tests, float, Floating Point
D is a systems programming language with support for garbage collection. Usually it is not necessary to free memory explicitly. Just allocate as needed, and the garbage collector will periodically return all unused memory to the pool of available memory.