Saturday, December 6, 2014

C# - Class vs Struct

For those who wonder why you'd ever need a struct instead of a class there is a simple answer; memory footprint!

Suppose you need a queue to store a lot of quotes in a sliding window, say in a queue<t>

public class Quote
{
public datetime TradeTime;
public double TradePrice;
public long TradeSize;
}

This data uses 3 x 8 = 24 bytes. So what happens if you add 100 million of these objects to the queue;

If uses up 5 GB of memory, a bit more than the 2.4GB the data would need for itself.

That's ofcourse because the queue keeps a pointer of 8 bytes (64bit OS) to each object and every object has another 16 bytes used for bookkeeping. See http://stackoverflow.com/questions/10655829/what-is-the-memory-overhead-of-a-net-object

Now we change our implementation;

public struct Quote
{
public datetime TradeTime;
public double TradePrice;
public long TradeSize;
}

Now our queue is only using 2.4GB!  


What lessons do we learn here;

- For large amounts of small objects consider using structs, even ones you create on the fly. 
- You can store about twice the amount of objects
- The Garbage Collector will bother you a lot less with a few millions less objects to collect
- Data is copied instead of referenced. But with small objects that is no performance issue