April 5, 2009

Structs

This week, structs came up for the second time in less than 2 months. I assume it is best to set the record straight for myself and hopefully others. The most important difference between classes and stucts has a lot to do with the different types of memory programmers have indirect access to. I admit I don't know a great deal about the differences between stack and heap memory, so I spent so time looking into both.

Stack Memory functions as a LIFO ordered stack. Allocation is simple and faster than heap allocation. The memory is also automatically reclaimed once it is out of scope, which beats the pants out of waiting on the garbage collector.

stack_heap

One major issue with the stack memory is that if the amount of memory required is significant and overruns what is available, you will get a stackoverflow. Another issue is that because memory is deallocated as soon as it is out of scope, data must be copied everywhere it is used. For example, whenever a struct is passed into a function, a new struct is created with the values of the copy. This is slower than just handling a reference to the memory and working with the data structure (class) in that fashion.

struct StructContainer
{
    public int x;
}
 
class ClassContainer
{
    public int x;
}
 
static void ChangeStructValue(StructContainer sc)
{
    sc.x = 5;
}
 
static void ChangeClassValue(ClassContainer cc)
{
    cc.x = 5;
}
 
static void Main(string[] args)
{
    StructContainer sc = new StructContainer();
    sc.x = 1;
 
    ClassContainer cc = new ClassContainer();
    cc.x = 1;
 
    ChangeStructValue(sc);
    ChangeClassValue(cc);
 
    Console.WriteLine("Struct: {0} \r\nClass: {1}", sc.x, cc.x);
}

Heap memory, on the other hand, is allocated through a pool or free store. Memory is accessed indirectly or through references. Memory allocation and deallocation is hidden from the developer through abstraction and when dealing with classes, involves a garbage collector.

Now, the functional differences between structs and classes are actually quite small. Both structs and classes can contain functions, methods and implement an interface. Both can have constructors, but a struct can only contain an empty constructor. Only classes support inheritance. Effectively, if you are just creating a very simple data structure that may need a method or two; it can be done using a struct or a class.

Just a note, structs can not only be expensive when passing around, due to copying, but they can also be expensive in terms of memory usage as the stack does not have infinite space. Because of their tendency to take up more memory than expected, especially if the struct is more than 16 Bytes; it is probably best to avoid using them unless you are really certain that you know what you are doing and their scope will not grow.

If you are interested in reading more about the stack and heap, I would recommend this article. This one is a fantastic read, but deals more specifically with the heap.

Identify And Prevent Memory Leaks In Managed Code

C# struct/class Differences

1 comments:

Jason Morse said...

Overall this is a comparison of value vs. reference types.

As you mentioned, I think structs should only be used for small and immutable objects. Messages, depending on the implementation, should probably not be structs IMO.

One thing that you didn't talk about was value type) in a method or a wrapping object boxing/unboxing. Whenever you use the struct (a (e.g. array) that takes a reference type (object-derrived) the struct will be copied to the heap anyways. Also, if one is using any reference types within the struct (e.g. string, arrays, etc.) they are already using the heap and simply performing a shallow copy when replicating the struct.

Post a Comment

 
Copyright © CodeCuriosity | Theme by BloggerThemes & frostpress | Sponsored by BB Blogging