I'm comparing the size taken by serializing an object with 3 bytes of data. I'm creating 9 X 104 X 104 = 97,344 instances and serializing them. I would expect the space taken to be around 292,032 bytes with some misc serialization header stuff. I'm making
the same mistake elsewhere so that accounts for the (N bytes) starting 1.4M larger.
This takes the minimal amount of space. (1,655,687 bytes)
[code]
[Serializable]
public class MyObject
{
public byte _a;
public byte _b;
public byte _c;
}
[/code]
Followed by an array: (3,115,802 bytes)
[code]
[Serializable]
public class MyObject
{
public byte[] _data = new byte[3];
public MyObject()
{
_data[0] = 0;
_data[1] = 0;
_data[2] = 0;
}
}
[/code]
Followed by a list: (5,354,993 bytes)
[code]
[Serializable]
public class MyObject
{
public List<byte> _data = new List<byte>();
public MyObject()
{
_data.Add(0);
_data.Add(0);
_data.Add(0);
}
}
[/code]
How can I get the a fixed array to use the same space as the 3 byte variables?
[code]
BinaryFormatter bf =
new BinaryFormatter();
bf.Serialize(fs, myObject);
[/code]
When I have an object with 3 bytes, I want it to take 3 bytes of disk space.
-
-
If you want a tight binary format, you could always do the serialization yourself, directly on the stream.
Writing a byte-array to a Stream:
fs.Write(data, 0, 3);
Reading a byte-array from a Stream:
byte[] data = new byte[3]; int offset = 0; while(offset < data.Length) offset += fs.Read(data, offset, data.Length - offset); -
It's worth noting that the array version requires at least 7 bytes (more on x64) in memory, as the pointer to the array is going to account for another 4.
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.