C# - 'new' and (lack of) 'delete' operators

Started by
5 comments, last by Promit 16 years, 10 months ago
Hey all, I've been programming in C++ for about 10 years, and have recently (last couple of weeks) decided to learn C#. Currently I'm getting my head around the differences. So far so good. One question which came up in my mind to which I could not easily find the answer on the web, is the lack of a 'delete' operator (as in C++). Some of the searching I did revealed that memory heap allocation is automagically recycled by the .NET garbage collector "periodically". The question in my mind is, "how periodically?". The reason I ask this is that, for the test app I'm creating, it's possible to initialize the same thread repeatedly; if I am simply making multiple calls to 'new', will the allocated object recycle properly? How does .NET handle multiple allocations internally?
Advertisement
Have a look at http://msdn.microsoft.com/msdnmag/issues/1100/gci/
Thanks! I'll check it out.
Also check out the IDisposable interface, you need to use it if you're using unmanaged resources (ie, resources from a native library like directx, sdl, etc).
And if you want to see when the garbage collector actually runs in your app, try CLR Profiler.

The non-technical answer to "how periodically" is: 'when it can'. If your program is running 100%, you're going to run into trouble (if you're allocating memory). The more free time the framework has, the more freedom the collector has.

will the allocated object recycle properly? Yes.
How does .NET handle multiple allocations internally? The way it has been explained to me is by having a reference graph. As nodes (or branches) of data can no longer trace a reference back to the root of the graph, the collector culls them. No cyclic reference problems that can crop up with reference counting.


The standard makes no stipulations, to my knowledge, about when the GC is run. However, the implementation typically runs the GC when it needs to; this usually means that an allocation request has been made and the gen0 section of the heap is full.

In other words, it'll happen when you use new, if necessary.
SlimDX | Ventspace Blog | Twitter | Diverse teams make better games. I am currently hiring capable C++ engine developers in Baltimore, MD.

This topic is closed to new replies.

Advertisement