I have an application that holds huge number of instances in-memory for performance reasons, and I don't want to write it to disk or any other place, just hold it all in-memory.
public class MyObject
{
public string Name;
public object Tag;
public DateTime DateTime1;
public DateTime DateTime2;
public DateTime DateTime3;
public long Num1;
public uint Num2;
public uint Num3;
public ushort Num4;
}
In many cases i actually don't using all the fields, or not taking the advantage of the field's whole size. so I Thought maybe transfer this whole class into an interface with properties, and make many implement classes that stores data in different ways: uses smaller fields (for example int instead of long) and omit some unused fields.
example:
public interface IMyObject
{
string Name { get; set; }
object Tag { get; set; }
DateTime DateTime1 { get; set; }
DateTime DateTime2 { get; set; }
DateTime DateTime3 { get; set; }
long Num1 { get; set; }
uint Num2 { get; set; }
uint Num3 { get; set; }
ushort Num4 { get; set; }
}
public class MyObject1 : IMyObject
{
public string Name { get; set; }
public object Tag { get; set; }
public DateTime DateTime1 { get; set; }
public DateTime DateTime2 { get; set; }
public DateTime DateTime3 { get; set; }
public long Num1 { get; set; }
public uint Num2 { get; set; }
public uint Num3 { get; set; }
public ushort Num4 { get; set; }
}
public class MyObject2 : IMyObject
{
private int _num1;
public string Name { get; set; }
public object Tag { get; set; }
public DateTime DateTime1 { get; set; }
public DateTime DateTime2 { get; set; }
public DateTime DateTime3 { get; set; }
public long Num1
{
get { return _num1; }
set { _num1 = (int)value; }
}
public uint Num2 { get; set; }
public uint Num3 { get; set; }
public ushort Num4 { get; set; }
}
public class MyObject3 : IMyObject
{
public string Name { get; set; }
public object Tag { get; set; }
public DateTime DateTime1
{
get { return DateTime.MinValue; }
set { throw new NotSupportedException(); }
}
public DateTime DateTime2 { get; set; }
public DateTime DateTime3 { get; set; }
public long Num1 { get; set; }
public uint Num2 { get; set; }
public uint Num3 { get; set; }
public ushort Num4 { get; set; }
}
// ...
Theoretically, with this method I can actually reduce memory footprint, But practically as you see, the problem with that approach is that it will result in Cartesian product of all cases with smaller and omitted fields, ugly and big code that can't be maintained after written in the future.
Another thought about the strings:
All strings in a .NET application represented in UTF-16 encoding. If i only could made it to be encoded in UTF-8 it would reduce x2 times the memory used by the strings.