Monday, February 04, 2008

Why doesn't c# have const?

One thing I really miss in c# is const. I know most of you are questioning me on this
I must say I am for const correctness, C++ developers argue you always get a library where some plod has forgot to use const correctness and you have to stick const_casts everywhere but I don't think this is a valid argument. Just because people don't use a language feature doesn't mean that language feature should not be provided. C# could have followed on from c++ in this regards and have a const_cast type thing. const as you are aware is a language feature rather then a runtime feature and In my opinion this sort of thing could have been added without effecting the .NET runtime

Perhaps Microsoft will introduce a c# version that does have const in the future but for now one has to rely on documentation to state a method is just an accessor or that parameter objects will not be changed by the called function


Its an interesting debate though
http://blogs.msdn.com/oldnewthing/archive/2004/04/27/121049.aspx

A guide to Garbage collection for a c++ programmer

For traditional C++ programmers it initially feels a little strange that one is calling “new” and not having to worry about calling delete and freeing the memory on objects. Don’t worry VB programmers have been doing this for years and see how memory efficient most VB applications areJ No seriously I am not advocating a carefree attitude towards memory when programming in .NET, far from it. If one is not careful you could have .NET application which is consuming unnecessarily huge amounts of memory and resources especially if .NET interacts with unmanaged code, which of course it always does. So it is critical to understand.

  • When the garbage collector kicks in.
  • How does GC mark and decide what is garbage
  • When and How does it free the garbage
  • ~MyClass() is not a C++ destructor it’s a Finaliser and gets called in a process called finalisation

GC only on allocation and the managed heap is full:

The first thing to know is the garbage collector only “kicks in” when the heap is full and “new” is called. If you have an infinite loop which is just accessing memory and never calling new the Garbage collector cannot kick in:

Lets look at some code lets declare a class MyObject which will occupy some memory

class MyObject

{

private static long m_count = 0;

private long m_id;

private string m_duffmemory;

public MyObject()

{

m_id = m_count++;

m_duffmemory = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

}

}

Ignore the fact that that this code is not threadsafe or that I have not done any sensible error handling. Ok lets create a program that will allocate these objects and put them in a list and then release them from the list. Lets monitor memory usage and see if and when the garbage collector kicks in when we are accessing the list in an infinite loop

static void Main(string[] args)

{

List<MyObject> m_objects = new List<MyObject>();

if (args.Length >= 1)

{

long size = System.Int32.Parse(args[0]);

Console.WriteLine("Allocating {0} objects, Initial Memory Usage {1} ....", size,

System.GC.GetTotalMemory(false));

Console.ReadLine();

for (long i = 0; i < size; i++)

{

m_objects.Add(new MyObject());

}

Console.WriteLine("Allocated {0} objects, Current Memory Usage {1} ....", size, System.GC.GetTotalMemory(false));

Console.ReadLine();

}

bool looped = false;

while (true)

{

if (looped == false)

Console.WriteLine("Freeing Objects Current memory usage {0},", System.GC.GetTotalMemory(false));

for (int i = 0; i < m_objects.Count; i++)

{

m_objects[i] = null;

}

if (looped == false)

{

Console.WriteLine("Current memory usage {0},", System.GC.GetTotalMemory(false));

looped = true;

}

}

Copy the class and the following program into a new console application project and run it up. If you monitor with Performance Montior or bring up Task Manager you will see the while loop is running but the memory usage is not going down. The garbage collector is not kicking in

You can also monitor the memory usage in Performance Monitor. Notice the Paged Bytes will remain the same


Ok now remove the last if(looped == false) check and run it up again. This way it will constantly print out the current memory usage. You will see that, initially the memory usage goes up, then after a while, the GC kicks in!

Notice the memory goes up despite collection being required This is because the collection only takes place when the managed heap is full


A Generational Heaps

The Managed heap is actually divided into 3 generations Gen 0 Gen 1 and Gen2. These heaps are compacted because .NET always knows the size of an object.


Figure 3.

The generations also keep a current location of where the next object is to be allocated.

Freeing the Garbage

We know the CLR is lazy and will only free memory when its needed on allocation so lets see what happens it needs to actually free memory. How does the Garbage collector decide what is garbage? From the Garbage collectors point of view everything is to be considered garbage unless its root (a reference or pointer to the object on the heap) is referenced directly or indirectly on the stack (statics, local variables and CPU registers) Ok so lets say the Garbage collector needs to free memory in order to fulfil the allocation request. A graph or good list is created of all objects which are referenced from the stack.

It is interesting to note that because of the heap generations the Garbage collector does not need to examine the entire heap. We know that the object will first need to be allocated on Gen 0. A Gen 0 collection needs to take place (since gen 0 is full) The objects that are on Gen0 that are referenced still have survived the collection so are promoted (actually moved) to Gen 1. Note the memory is copied from generation heap to generation heap using standard CopyMemory. It can do this because the CLR knows the size of an object. This is why .NET objects have to be pinned if their memory is being passed to unmanaged code

If not referenced then the object is subject to garbage collection the memory is reacclaimed and the “Next Object pointer is reset”. This is the process of a Gen 0 collection

Note if in the promotion the Gen 1, Gen 1 is full. A Gen 1 collection needs to take place (survived objects move to Gen 2) and the same process is followed as for Gen 0 collection and is compacted in the same manner.

Therefore we can see the longer an object stays alive it will eventually end up on Gen 2 (the maximum generation) as collections take place

Also we can see short lived objects they are usually freed on a Gen 0 or Gen 1 collection which are inexpensive However Gen 2 collections are expensive because they involve a Gen 0 and Gen 1 collection also

Note objects over a certain size (I believe its 84K) are not allocated to the Generation heap. The CLR has specific memory (the large memory space) for this which mirrors the standard C runtime heap (i.e. its not compacted like the generation heaps). This is only collected when Gen 2 collections take place

Before the memory is freed The CLR needs to call Finalise for objects that have finalizer before it can reacquire the memory so these objects have togo through a process called Finalisation first before they are subject to collection

Finalization

The Garbage collector has two queues. the Finalization queue and the Freechable Queue. if an object has a finalizer then a pointer is assigned on the Finalization Queue when it is created. When considered garbage the GC checks to see if the object is in the Finalization Queue, if so the pointer is moved to the freechable Queue. For objects on the Freechable queue the Finalisation thread calls the Finalizer and removes the object from the freechable queue and the memory will get freed the next time a GC will occur. It is important to understand objects with Finalizers will possibly go through one or more collection cycles before memory is reclaimed. Microsoft also state for this reason state that you cannot make any assumptions about the order of finalization. Note also the finalizer always gets called be called by another thread (the finalization thread)

Ok so lets get into the real debate about garbage collection C++ programmers argue that all this walking the of roots tree and the finalization process will interrupt the program to free memory and compact the heap. That is true, Certainly one also has to bear in mind that .NET threads must get suspended whilst finalization occurs. However one has to bare in mind that C++ programmers don’t have control how the C runtime manages the heap time is also spent in the heap management algorithms of the c runtime I would advise that if you need to performance tune so much that you need to write your own heap allocation rather then use the standard C runtime heap or you have performance tuned your code so that all dynamically allocated memory up front or just using objects on the stack then you could possibly argue that C++ code will be faster. However if you find you do not require such optimisation and the C++ is constantly allocating and freeing objects on the heap and there are the risks of leaks etc to consider how can one ensure that this will be any faster? Perhaps the overhead of the heap allocation may be more costly overall then the short suspensions which only occur if the Gen 2 collections need to take place. We know Gen 0 collections are very cheap and are done as part of the allocation process

Rules:

If you are referencing unmanaged resources such as native objects, File handles then you must Implement the IDispose interface i.e. dispose method

Dispose should always call SurpressFinalize

If you implement the Dispose interface then you should have a Finalizer defined (since the object may be referenced for a long time) otherwise you should not

Recommendations

Never keep reference to objects unless you really have to.

Try to write code with the garbage collector in mind. Read the following recommendations from Microsoft

http://msdn2.microsoft.com/en-us/library/ms973837.aspx

For more information and my sources

Anyway The following article http://www.devcity.net/Articles/46/1/garbage_collector.aspx

Explains the GC algorthim

www.codeproject.com/dotnet/garbagecollection.asp?msg=341687
It also explains how Weak References work

Friday, March 09, 2007

.NET compiled or interpreted?

How can C# be as fast as C++. C/C++ is compiled direct to machine code all the calls are linked at link time before the program is run Surely C# will be slower because code has to be compiled on the fly i.e. as it is executed. How can interpreted code be faster then pre compiled code?

This is true .NET assemblies do not contain machine code they contain a op codes similar to what a compiler generates in the form of MSIL (Microsoft Intermediate language). Microsoft provide a tool to view the MSIL in assemblies called ILDASM (Intermediate Language Disassembler)

The CLR reads this MSIL and “just in time” compiles into machine code on a method by method, call by call basis

The key thing to remember however is once. The CLR has JITTED the MSIL the machine code remains cached in memory if the same methods are called the CLR knows it has already compiled this code and will call the machine code directly. therefore .NET can not be considered as interpreted

Therefore yes the first c# call to a method will be slower but once it is JIT it will be just as fast as any other compiled method in C++ or C.

Note Microsoft provide a tool called NGEN which will actually compile and convert the MSIL assembly into native machine code. Please note that all the system .NET libraries provided by Microsoft in the GAC global assembly cache have already been NGEN and so are in native machine code. Before you go and NGEN all your assemblies consider that it may be slower for the CLR to load the entire assembly machine code rather then JIT the small portion of the code that gets called. Also bare in mind you are tying your assembly to a particular platform and processor architecture.

Have a read through

http://channel8.msdn.com/Posts/MSIL-the-language-of-the-CLR-Part-1

http://channel8.msdn.com/Posts/MSIL-the-language-of-the-CLR-Part-2

http://channel8.msdn.com/Posts/MSIL-the-language-of-the-CLR-Part-3

This article also goes into detail about the physical layout of an assembly

http://www.informit.com/articles/article.aspx?p=25350

Friday, June 16, 2006

Common issues and traps of C# for a C++ programmer

The most noticeable thing about C# is the difference between reference types and value types.


Value types are types allocated and passed on the stack,
things like: int,char,double,enum etc

Reference types are types which are managed i.e. class, delegate and are allocated on the GC managed heap (subject to garbage collection)

Boxing

Boxing is taking a value type (on the stack) and assiging it to a reference type (onto the managed heap)

example:

object x = new object;
x = 10;

Here a 10 is actually copied across from the stack onto the managed heap memory

Unboxing

Unboxing taking a value from a managed object (on the managed heap ) and assigning to a value on the stack

void
function (object obj)

if (obj is int)
{
int x = (int) obj;
....
}

Being a C++ programmer you know when an object is on the stack or on the heap However in C# you seem to be given choice only at the type declaration level and you have to realise when boxing and unboxing is taking place because it is ofcourse slower since memory has to be copied rather then simple memory assignment.
The Java community argue that it should be up to the runtime to decide when objects are passed by value(on the stack) or should be allocated on the heap. But what I don't understand is how can the runtime know when this object is to be passed by value? Perhaps a Java VM Guru can explain how the Java VM decides surely there are performance implications when the object has to be copied from the stack to the heap?

Anyway The key difference between C++ and C# is a struct is a value type (on the stack) a class is a managed reference type (on the heap)

Choosing if a type should be a struct (stack) or a class (heap) has to be done very carefully

I have been bitten by this! take a look at the following code:

private List < SomeType > mListOfSomeType;

void MarkDataAsDirty(bool dirty)
{
foreach(SomeType member in mListOfSomeType)
{ member .Dirty = dirty; }
}

if SomeType is a struct, The above code will not actually set the dirty flag on the members of the list
In order to acheive this one has to change the code to.

void MarkDataAsDirty(bool dirty)
{
for(int i = 0; i < mListOfSomeType.Count; i++)

{ mListOfSomeType[i].Dirty = dirty; }
}

Here are the ten common traps C++ programmers fall into when writing c# code (the struct and class issue is one of them)

http://www.ondotnet.com/pub/a/oreilly/dotnet/news/programmingCsharp_0801.html

Background

I have started this blog as a diary of my findings of C# as a C++ programmer.

The blog assumes you are familiar with C++ and c# and goes into quite some depth.

I am well aware each tool has its own purpose C++ is a very powerful language but one has to appreciate that is all it is, a language. This is not really a comparison of the languages but a relflection on common issues that a developer encounters working with these languages.


This blog will probably end up with:


  • References to material that is useful to understand C# programming for a C++ programmer
  • Features of .NET that I find extreemly useful that can never exist in a traditional C++ development environment
  • A wish list of what I would like in C# as a developer using an OO language that I have in C++

Before reading the rest of the blog I suggest you read the following article which gives an overview of C# for a C++ programmer

http://msdn.microsoft.com/msdnmag/issues/01/07/ctocsharp/