2008-04-05

Heap or stack -- struct vs. class declaration and the influence on performance in .NET

The XmlSerializer namespace in .NET requires the XML structure of a document to be declared as a class or struct. In fact many examples in the wild use the class method to serialize a XML document, which has major disadvantages. One of these disadvantages is that good coding style requires one separate source file for each class to be created, which can make the source tree very large. However the main disadvantage is the performance overhead created by the declaration of an unnecessary class that determines the structure of the XML document. The reason for this performance overhead is the high consumption of memory which is required in .NET for every class which is stored on a stack.

The solution is quite simple: Refactor the according classes to structs. The data structure "struct" requires only a heap in .NET which consumes less memory.