views:

289

answers:

2

I would have thought that it would be clear cut whether memory allocation is faster in managed code than in native code - but there seems to be some controversy. Perhaps memory management under a Virtual Machine be faster because of no context-swapping calls to the OS, but then I see that the VM would itself need to make periodic calls to the OS for more memory, and it has the management overheads the memory itself rather than the OS.

Rather than making unsubstantiated assertions like I have, please provide links to references that support your position.

+1  A: 

Listen to Jeff Richter of Wintellect, he's an authority on the subject:

http://www.dotnetrocks.com/default.aspx?showNum=361

Kev
+6  A: 

Take a read of http://msdn.microsoft.com/en-us/library/ms973852.aspx

It goes into some details on how memory allocation works in .NET and briefly compares it to the C++ model.

In summary, memory allocation in .NET involves grabbing the current stack point as the object's address and adding the object's data size to the stack pointer. C++ by comparison has to search through a list of freed pointers for an area of the heap large enough for the object. In most cases therefore, .NET will be faster.

David Arno
Wouldn't that lead to an ever-growing stack? And stack fragmentation?
Josh
Josh, that is where garbage collection comes in. It removes de-referenced objects from the heap, then moves all the remaining objects to make it a contiguous block of used memory once more, then updates all affected references with the new pointer values.
David Arno
So memory allocation is fast in managed code, but the slowness of occasional garbage collection events is the trade-off.
David Arno
From the article: "Reference types and boxed value types live in the heap. They are addressed by object references, which are simply machine pointers just like object pointers in C/C++." In native C++, the heap is supplied by the OS; is it supplied by the VM in .NET?
Josh
In native C++, you can manage your own heap by grabbing a big chunk of memory and overriding new and delete, but most people do just let the OS manage it as you say. In managed code, the VM has to manage it itself, so it will grab a big chunk of memory for its own locally managed heap.
David Arno