Allocate CString on heap – Does that saves memory and improve performance?

24 06 2008

“Objects – The stack’s worst enemy. The stack is only indented for light weight datatypes such as int, float etc. So if you want to allocate a lot of objects, allocate on Heap. Or else stack will overflow”

This is the golden rules that beginners learn first, while stepping into professional C++ development. While considering objects, CString instances are the most common ones used in almost all MFC applications and for improving performance and for saving memory, usually we used to allocate it on heap. But, does that saves memory and improve performance? Well, its a myth. Want to know why?


First of all check the following code snippet and answer me, whether the message box will be shown or not?

// CString size == int size?
if( sizeof(CString) == sizeof(int))
{
    // I can't believe it.
    AfxMessageBox(_T("Am I dreaming?"));
}

Yes! It’ll be shown and the size of CString is just 4 bytes. Actually CString just contains LPTSTR as member. CString always allocate the string on heap. So while allocating CString itself on heap, you’re really degrading performance by extra heap allocation and more over you’ve to manage the pointer which can lead to memory leaks.


Don’t think that all objects are good candidates for heap. There can be exception like our CString. 😉


Targeted Audience – Intermediate.

Advertisements