Monday, May 5, 2008

Optimizing Storage for Constant Data

In programs we usually declare constant string data. Like..

const char* g_pchar = "this is a string";

You might be knowing that if we run multiple copies of a exe or dll, the code portion is not duplicated per process. So do the constant data. This is because the constant datas are stored in a special section of exe called ".rdata"( The code protion is stored in the ".text" section ). But guess what will happen if we have declaration like..

const CString g_str("this is the worst thing I can do");

Now you've got the CString object (which is quite small) in the .bss section( .bss section stores nonconstant uninitialized data ), and you've also got a character array in the .data section( Nonconstant initialized data ), neither of which can be backed by the EXE file. To make matters worse, when the program starts, the CString class must allocate heap memory for a copy of the characters. You would be much better off using a const character array instead of a CString object. So never ever declare like that ( Reference "Programming Microsoft vc++" by David Kruglinski ).

OK that was the theory. Now the reason why I stated the above theory is that, last week, I installed the latest VS 2008 feature pack. This feature pack had some new classes for MFC. So I decided to check out the new classes. The CWinAppEx is on among them. On the very first function I stepped in( constructor of the CWinAppEx ), I found the following piece of code..

const CString strRegEntryNameWorkspace = _T("Workspace");
m_strRegSection = strRegEntryNameWorkspace;

ops . And when I scrolled up, there was another bunch of similar codes

static const CString strRegEntryNameControlBars = _T("\\ControlBars");
static const CString strWindowPlacementRegSection = _T("WindowPlacement");
static const CString strRectMainKey = _T("MainWindowRect");
static const CString strFlagsKey = _T("Flags");
static const CString strShowCmdKey = _T("ShowCmd");
static const CString strRegEntryNameSizingBars = _T("\\SizingBars");
static const CString strRegEntryVersion = _T("ControlBarVersion");
static const CString strVersionMajorKey = _T("Major");
static const CString strVersionMinorKey = _T("Minor");

I dont think any one has seen such a badly written, poor quality code in the old MFC 4 code. Never did I. If MFC starts like this, where will the developers using MFC ends?

When I discussed about this in code project and MSDN forum, I got some interesting response. That's how I came to here about Wirth's law[^] , which states

Software gets slower, faster than hardware gets faster.
Software is decelerating faster than hardware is accelerating.

Very true and you just saw one example.