I haven’t been programming for very long and am new to C/C++. I’ve always used C# in the past, but I’ve switched to native code to write my first Win32 API application. I started in C but became increasingly maddened by trying to work without classes.
I’ve started porting some of the C to C++. Initially, I had the project setup as VC++ using .NET 4. About 25% of the way through porting, I ran the program in debug mode. I was shocked. According to Task Manager, the program uses more than twice the amount of memory as the C version. I then de-.NETified the project and was even more surprised: using only the STL, my application needed 33% of the memory required for the .NET incarnation. Here are the numbers:
Memory Usage
Complete App in C:……………940kb
25% Port in VC++/.NET4:……2.1MB
25% Port in C++:……………….700kb
If I put the other features of .NET aside, I’m left wondering what the advantage of managed memory is if it trebles the memory footprint. Is it the preemption of leaks? Safer pointers?
Thanks
Some of the memory footprint you are seeing will belong to the .Net Framework’s runtime too.
Garbage collection helps eliminate a lot of programming overhead such as remembering to dealloc memory or to release objects. I’ve programmed a lot in C, Objective C and C# and I can certainly say that whilst garbage collection doesn’t solve every issue, it does remove a lot of responsibility on me and allows me to concentrate on logic rather than hunting for an exra release instruction.
I also think that the allocation mechanism for new objects is very fast as it always adds to the end of the memory address rather than having to search for blocks large enough.
I should say that whilst garbage collection is great, it’s not perfect and has it’s own limitations in .Net, especially when dealing with unmanaged code i.e. not calling dispose can leave memory lingering around until finalization. The collection cycles can also be costly as all activity is suspended for the duration of garbage collection.
As with any technology, understand the benefits and pitfalls and choose appropriately.