Two days ago I posted a simple implementation of a game of colors. Though it was intended only as an exercise, someone has criticizes the use of an int** to hold the grid information, mainly for two reasons:
- the footprint on 64-bit platforms can get nasty
- the explicitly allocated memory, instead of using a std::vector
So this is the code:
int** m_pCells;
void Create()
{
m_pCells = new int*[m_nSize];
for(int i = 0; i < m_nSize; ++i)
m_pCells[i] = new int[m_nSize];
}
Let’s see how much memory it takes. The total size should be:
totalsize = sizeof(m_pCells) + sizeof(m_pCells[0]) * m_nSize + m_nSize * m_nSize * sizeof(int);
On 32-bit platforms, the size of a pointer is the same with the size of int and is 4 bytes. For the maximum size allowed for my grid, which is 50, the total size in bytes for the grid is: 4 + 4*50 + 50*50*4 = 10204.
On 64-bit platforms, the size of a pointer is 8 bytes, but the size of int is still 4 bytes. So for a grid with 50 rows and columns it needs: 8 + 8*50 + 50*50*4 = 10408 bytes. That’s a 2% increase of required memory.
The memory footprint was the last thing I had in mind when I wrote this simple exercise. Well, of course there is a way to require only 4 more bytes on 64-bit platforms. And that is using an int* allocating m_nSize*m_nSize elements.
int* m_pCells;
void Create()
{
m_pCells = new int[m_nSize * m_nSize];
}
void Destroy()
{
delete [] m_pCells;
m_pCells = NULL;
}
With this implementation, when you need to access the element at row i and column j, you have to use m_pCells[i * m_nSize + j].
As for the second argument, that explicitly using operator new[] to allocate memory instead of using a vector of vectors, well, what could I say? Sure, why not. Different people use different programming styles. As long as all implementation are correct and achieve the same goal with similar performance, I guess everyone is entitle to code as he/she wants. But if we go back to the memory footprint, I would also guess that the use of vectors would take more memory than pointers to int, because the size of a vector is several times the size of a pointer. But I wouldn’t say that’s an important issue here.
Anyway, these arguments remember me the joke (or maybe it’s serious) about the rules of optimization:
- Don’t optimize.
- Don’t optimize yet (for experts only).
(Of course there are super experts that can ignore these rules.)









