如果您不想采取自己编写序列化程序的方式,您可以使用protobuf.net序列化器。下面是一个小测试程序的输出结果:
Using 3000 parents, each with 5 children
BinaryFormatter Serialized in: 00:00:00.1250000
Memory stream 486218 B
BinaryFormatter Deserialized in: 00:00:00.1718750
ProfoBuf Serialized in: 00:00:00.1406250
Memory stream 318247 B
ProfoBuf Deserialized in: 00:00:00.0312500
这应该是相当易懂的。这只是一个运行,但是相当有指示性,我看到了加速(3-5倍)。
要使您的结构可序列化(使用protobuf.net),只需添加以下属性:
[ProtoContract]
[Serializable]
public struct Child
{
[ProtoMember(1)] public float X;
[ProtoMember(2)] public float Y;
[ProtoMember(3)] public int myField;
}
[ProtoContract]
[Serializable]
public struct Parent
{
[ProtoMember(1)] public int id;
[ProtoMember(2)] public int field1;
[ProtoMember(3)] public int field2;
[ProtoMember(4)] public Child[] children;
}
更新:
事实上,编写自定义序列化程序非常容易,以下是一个基本实现:
class CustSerializer
{
public void Serialize(Stream stream, Parent[] parents, int childCount)
{
BinaryWriter sw = new BinaryWriter(stream);
foreach (var parent in parents)
{
sw.Write(parent.id);
sw.Write(parent.field1);
sw.Write(parent.field2);
foreach (var child in parent.children)
{
sw.Write(child.myField);
sw.Write(child.X);
sw.Write(child.Y);
}
}
}
public Parent[] Deserialize(Stream stream, int parentCount, int childCount)
{
BinaryReader br = new BinaryReader(stream);
Parent[] parents = new Parent[parentCount];
for (int i = 0; i < parentCount; i++)
{
var parent = new Parent();
parent.id = br.ReadInt32();
parent.field1 = br.ReadInt32();
parent.field2 = br.ReadInt32();
parent.children = new Child[childCount];
for (int j = 0; j < childCount; j++)
{
var child = new Child();
child.myField = br.ReadInt32();
child.X = br.ReadSingle();
child.Y = br.ReadSingle();
parent.children[j] = child;
}
parents[i] = parent;
}
return parents;
}
}
当在一个简单的速度测试中运行时,它的输出如下:
Custom Serialized in: 00:00:00
Memory stream 216000 B
Custom Deserialized in: 00:00:00.0156250
显然,这种方法比其他方法的灵活性要少得多,但如果速度真的很重要,它比protobuf方法快2-3倍。它还可以产生最小的文件大小,因此写入磁盘应该更快。
children
字段不是值类型。 - H H