The other day (actually let's say a long long time ago) I was reading the excellent CLR via C# book (4th Edition) which I strongly recommend to anybody who is doing some C# development to better understand the underlying mechanisms and explains the magic behind the scenes.
Since that reading I started to become over-worry about whether I should use structs over classes in my design decisions.
I have a situation that would make a perfect use of the structs (fast communication of temporary data chunks(aka the structures)).
However, I'm still struggling about using the structs in this scenario since I've seen so many rules of the thumb. For instance, the instance must be smaller than 16 bytes or the fact that I'm willing to carry an array or a string (which at least is immutable) as one of the structure fields while the String need somehow to be garbage collected later on, etc.
It seems like that the use of structs is then really more than limited.
Here is below an oversimplified C# 6 example, I guess the answer about memory efficiency is here: no, please don't use struct cause you're going to end up with a lot wasted memory and passing that as argument is going to be really greedy, performance-wise.
public enum ChunkHeader : ushort
{
Unknown = 0x00,
Transmitted = 0x01,
Received = 0x02,
}
public struct Chunk
{
public static Chunk Empty = new Chunk(ChunkHeader.Unknown, new Byte[0]);
public Chunk(ChunkHeader header, Byte[] data)
{
this.Header = header;
this.Data = ExceptionHelpers.ThrowIfNull(data, nameof(data))
}
// C# 6 read-only >>auto<<-properties
public ChunkHeader Header { get; }
public Byte[] Data { get; }
}
public static class ExceptionHelpers
{
public static T ThrowIfNull<T>(T parameterValue, String parameterName)
{
if ((Object)parameterValue == null)
{
throw new ArgumentNullException(parameterName);
}
else
{
return parameterValue;
}
}
}
My question is fairly simple, do you think that the structure above can be memory efficient in terms of Garbage Collection? Or is it still better to go with a class definition considering the underlying reference type field in the structure?
If so, any workarounds or general guidelines for dealing with a lot of chunks of data in order to prevent massive garbage collections?
Please consider that those chunks of data are intended to be used only for a short amount of time.