Why you should care about memory

As a programmer, you're probably already used to using new and delete (or malloc and free if you're writing C), and you may be wondering why you would want to handle memory by yourself when it's already built into the language and is easy to use. Well, the first thing is that like most aspects of using a high-level programming language, you do not know what is going on behind the scenes. If you write your own logic to handle memory, you can create your own statistics and additional debugging support, such as automatically initializing data. You can also check for things such as memory leaks.

However, for game developers the most important aspect to look into is that of performance. Allocating memory for a single object or thousands of them at once is approximately the same time as the computer needs to look through your computer's memory for an opening that isn't being used, and then give you the address to the beginning of that contiguous piece of memory. If you keep requesting small pieces of memory over and over again this can lead to memory fragmentation, which is to say that there isn't enough free continuous space when you want to get a larger object.

We may start off with some memory like this, with the gray sections being free memory and black being memory set aside because we called new for that amount of data. Each time we call for new, the computer needs to look for the first address that is open which has enough space to fit the object type we provide:

Later on, we remove some of the memory and that opens up some space, but the computer will need to look at each address and spend more time searching:

Finally, we get to a spot where we have very little open data and it requires a lot of work to find a place to insert new data, due to the memory becoming fragmented.

This is especially important if you are developing titles for a console or for a mobile device, as the size of memory you have to work with is much smaller than what you're used to working with on a PC. If you used computers five or more years ago you may remember the idea of defragging your computer, in which your computer would shift pieces of memory over in order to create larger blocks that could be used later. But this was a very time-consuming process.

Mach5 doesn't easily give us the ability to support having game objects being created in this way but, if you are interested in doing this, we do have a way that can use the concepts of an object pool in order to not waste resources; we will discuss that later on in the chapter.

An excellent article on writing memory managers for game programming can be found at http://www.gamasutra.com/view/feature/2971/play_by_play_effective_memory_.php.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.128.105