我冒昧地将您的课程输入CGbR生成器。由于它DateTime
尚处于早期阶段,尚不支持,因此我只是将它替换为long。 生成的序列化代码如下所示:
public int Size
{
get
{
var size = 24;
size += Cts == null ? 0 : Cts.Count * 4;
size += Tes == null ? 0 : Tes.Count * 4;
size += Code == null ? 0 : Code.Length;
size += Message == null ? 0 : Message.Length;
return size;
}
}
public byte[] ToBytes(byte[] bytes, ref int index)
{
if (index + Size > bytes.Length)
throw new ArgumentOutOfRangeException("index", "Object does not fit in array");
GeneratorByteConverter.Include((ushort)(Cts == null ? 0 : Cts.Count), bytes, ref index);
if (Cts != null)
{
for(var i = 0; i < Cts.Count; i++)
{
var value = Cts[i];
value.ToBytes(bytes, ref index);
}
}
GeneratorByteConverter.Include((ushort)(Tes == null ? 0 : Tes.Count), bytes, ref index);
if (Tes != null)
{
for(var i = 0; i < Tes.Count; i++)
{
var value = Tes[i];
value.ToBytes(bytes, ref index);
}
}
GeneratorByteConverter.Include(Code, bytes, ref index);
GeneratorByteConverter.Include(Message, bytes, ref index);
GeneratorByteConverter.Include(StartDate.ToBinary(), bytes, ref index);
GeneratorByteConverter.Include(EndDate.ToBinary(), bytes, ref index);
return bytes;
}
public Td FromBytes(byte[] bytes, ref int index)
{
var ctsLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
var tempCts = new List<Ct>(ctsLength);
for (var i = 0; i < ctsLength; i++)
{
var value = new Ct().FromBytes(bytes, ref index);
tempCts.Add(value);
}
Cts = tempCts;
var tesLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
var tempTes = new List<Te>(tesLength);
for (var i = 0; i < tesLength; i++)
{
var value = new Te().FromBytes(bytes, ref index);
tempTes.Add(value);
}
Tes = tempTes;
Code = GeneratorByteConverter.GetString(bytes, ref index);
Message = GeneratorByteConverter.GetString(bytes, ref index);
StartDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
EndDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
return this;
}
我创建了一个示例对象列表,如下所示:
var objects = new List<Td>();
for (int i = 0; i < 1000; i++)
{
var obj = new Td
{
Message = "Hello my friend",
Code = "Some code that can be put here",
StartDate = DateTime.Now.AddDays(-7),
EndDate = DateTime.Now.AddDays(2),
Cts = new List<Ct>(),
Tes = new List<Te>()
};
for (int j = 0; j < 10; j++)
{
obj.Cts.Add(new Ct { Foo = i * j });
obj.Tes.Add(new Te { Bar = i + j });
}
objects.Add(obj);
}
我的机器在Release
构建中的结果:
var watch = new Stopwatch();
watch.Start();
var bytes = BinarySerializer.SerializeMany(objects);
watch.Stop();
大小: 149000字节
时间: 2.059毫秒 3.13毫秒
编辑:从CGbR 0.4.3开始,二进制序列化程序支持DateTime。不幸的是,该DateTime.ToBinary
方法非常缓慢。我很快将用更快的速度代替它。
Edit2:当DateTime
通过调用使用UTC时,ToUniversalTime()
性能得以恢复,并且时钟为1.669ms。