D programs typically use a garbage collector that can make memory management both easier and more efficient. With the garbage collector, you don't have to keep track of object ownership and can defer free memory to a later point, which can boost performance.
However, while the garbage collector is useful, it doesn't absolve you of all thought in the area of memory management, especially when performance is important. In tight loops, you'll want to avoid the garbage collector. The way to do this is to avoid garbage collection allocations. No garbage collection allocation means no garbage collection cycle.
In order to avoid the garbage collector, perform the following steps:
new
expressionscope
in the function's parameter liststatic
and immutable
array literal initializersscope
in the function definitionThe D garbage collector only runs at program termination and when a garbage collector allocation is attempted. It doesn't have enough available memory to fulfil the request. Garbage collector allocations are not necessarily easy to find. The syntax may not stand out or they may be hidden behind library functions; however, if you successfully avoid these language constructs, you will successfully avoid the garbage collector.
You'll still have to manage your resources. We'll look at various techniques to help with this throughout the rest of this chapter.
Can we write a program without a garbage collector at all? Yes, in fact, we can write D programs that use the majority of the language, yet don't use the full D runtime or standard library at all and will even work on bare metal without an operating system. However, since this severely limits your library choices, it isn't always a practical option.
3.136.233.153