Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating an array replacement


Many operations on D's built-in array slices use the garbage collector. If you want to use alternate resource management strategies, you'll want a replacement type, which implements operators that can be used with the other strategy and disables those that cannot be used. It is possible to avoid all allocations using a static stack buffer, which can give a considerable performance improvement. We'll create an array replacement, which uses a static buffer for a predicted size and grows into a dynamically allocated buffer, if required.

How to do it…

To create an array replacement, perform the following steps:

  1. Define a struct that takes an element type and expected size.

  2. Define variables with the key components: a static buffer with the expected size, a slice to the current buffer, and the current length.

  3. Write a destructor to free the memory, if you are managing it manually.

  4. Overload the convenience operators you want on the array: length, capacity, reserve, append...