Introduction
Writing effective code is one of the most important and challenging responsibilities of a programmer. High-level programming languages like C++ hide a lot of things from a programmer, that you can hardly guess what exactly will be your compiled code. A simple call to a function in C++ could be dozens of lines of machine code, but you don't need to care because your computer can process billions of lines of machine code in a second; but when it comes to video game programming, everything changes, and that's because you have limited time and a lot of objects to process.
Memory Allocation
A simple optimization technique that I want to talk about here is about memory allocation and deallocation of fixed multi-dimensional arrays. Here is a simple code to allocate and free a two dimensional array:
T **data = new T*[sizeX];
for(int i=0;i<sizeX;i++){
data[i]=new T[sizeY]
}
for(int i=0;i<sizeX;i++){
delete [] data[i]
}
delete [] data;
But if your array is fixed and you don't plan to change its size, then it's not the most efficient way to do it. Consider you want to allocate a 100*10 array. To allocate and free this amount of memory, you should call new and delete operators 101 times, and that takes a lot of CPU time; but with a little change to your code, you can optimize it so that one call to new and delete does all the job. Here is my implementation:
class FixedArray
{
public:
template<class T>
static T **New(int sizeX, int sizeY)
{
int sizeAddress = sizeof(T*)*sizeX;
int sizeData = sizeof(T)*sizeX*sizeY;
char *data = new char[sizeAddress+sizeData];
for(int i=0;i<sizeX;i++){
((T**)data)[i] = &((T*)(data+sizeAddress))[i*sizeY];
}
return (T **)data;
}
static void Delete(void *p)
{
delete [] p;
}
};
You've got the idea, but if you are looking for a universal code, check Boost MultiArray.