Game Development Reference
In-Depth Information
If you decide to write your own memory manager, keep the following points in mind:
n Data structures: Choose the data structure that matches your memory alloca-
tion scenario. If you traverse a large number of free and available blocks very
frequently, choose a hash table or tree-based structure. If you hardly ever tra-
verse it to find free blocks, you could get away with a list. Store the data struc-
ture separately from the memory pool; any corruption will keep your memory
manager
s data structure intact.
n Single/multithreaded access: Don
'
t forget to add appropriate code to protect
your memory manager from multithreaded access if you need it. Eliminate the
protections if you are sure that access to the memory manager will only happen
from a single thread, and you
'
ll gain some performance.
n Debug and testing: Allocate a little additional memory before and after the
block to detect memory corruption. Add caller information to the debug mem-
ory blocks; at a minimum, you should use __FILE__ and __LINE__ to track
where the allocation occurred.
'
One of the best reasons to extend the C runtime memory manager is to write a better
system to manage small memory blocks. The memory managers supplied in the C
runtime or MFC library are not meant for tiny allocations. You can prove it to your-
self by allocating two integers and subtracting their memory addresses as shown here:
int *a = new int;
int *b = new int;
int delta1 = ((int)b - (int)a) - sizeof(int);
The wasted space for the C runtime library was 28 bytes for a release build and 60 bytes
for the debug build under Visual Studio. Even with the release build, an integer takes
eight times as much memory space as it would if it weren
t dynamically allocated.
Most games overload the new operator to allocate small blocks of memory from a
reserved pool set aside for smaller allocations. Memory allocations that are larger
than a set number of bytes can still use the C runtime. I recommend that you start
with 128 bytes as the largest block your small allocator will handle and tweak the size
until you are happy with the performance. I ' ll show you a simple memory pool class
later in this chapter in the
'
Memory Pools
section.
Grab Bag of Useful Stuff
Every programmer I know has a collection of gems that they use in nearly every
project. As you grow in your programming abilities, you
'
ll find yourself doing the
same thing. I want to share a few of the ones I
'
ve found or developed over the
 
 
Search WWH ::




Custom Search