提高大型结构列表的二进制序列化性能
本文关键字:二进制 序列化 性能 列表 高大型 结构 | 更新日期: 2023-09-27 18:00:17
我有一个用3 int表示三维坐标的结构。在一次测试中,我整理了一个列表<>100万个随机点,然后使用二进制序列化到内存流。
内存流的大小约为21MB,这似乎非常低效,因为1000000点*3个坐标*4个字节的最小值应为11MB
在我的测试设备上也需要大约3秒。
有什么改进性能和/或尺寸的想法吗?
(如果有帮助的话,我不必保留ISerializable接口,我可以直接写到内存流中)
EDIT-根据下面的答案,我对BinaryFormatter、"Raw"BinaryWriter和Protobuf 进行了系列化决战
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using ProtoBuf;
namespace asp_heatmap.test
{
[Serializable()] // For .NET BinaryFormatter
[ProtoContract] // For Protobuf
public class Coordinates : ISerializable
{
[Serializable()]
[ProtoContract]
public struct CoOrd
{
public CoOrd(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
[ProtoMember(1)]
public int x;
[ProtoMember(2)]
public int y;
[ProtoMember(3)]
public int z;
}
internal Coordinates()
{
}
[ProtoMember(1)]
public List<CoOrd> Coords = new List<CoOrd>();
public void SetupTestArray()
{
Random r = new Random();
List<CoOrd> coordinates = new List<CoOrd>();
for (int i = 0; i < 1000000; i++)
{
Coords.Add(new CoOrd(r.Next(), r.Next(), r.Next()));
}
}
#region Using Framework Binary Formatter Serialization
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Coords", this.Coords);
}
internal Coordinates(SerializationInfo info, StreamingContext context)
{
this.Coords = (List<CoOrd>)info.GetValue("Coords", typeof(List<CoOrd>));
}
#endregion
# region 'Raw' Binary Writer serialization
public MemoryStream RawSerializeToStream()
{
MemoryStream stream = new MemoryStream(Coords.Count * 3 * 4 + 4);
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(Coords.Count);
foreach (CoOrd point in Coords)
{
writer.Write(point.x);
writer.Write(point.y);
writer.Write(point.z);
}
return stream;
}
public Coordinates(MemoryStream stream)
{
using (BinaryReader reader = new BinaryReader(stream))
{
int count = reader.ReadInt32();
Coords = new List<CoOrd>(count);
for (int i = 0; i < count; i++)
{
Coords.Add(new CoOrd(reader.ReadInt32(),reader.ReadInt32(),reader.ReadInt32()));
}
}
}
#endregion
}
[TestClass]
public class SerializationTest
{
[TestMethod]
public void TestBinaryFormatter()
{
Coordinates c = new Coordinates();
c.SetupTestArray();
// Serialize to memory stream
MemoryStream mStream = new MemoryStream();
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(mStream, c);
Console.WriteLine("Length : {0}", mStream.Length);
// Now Deserialize
mStream.Position = 0;
Coordinates c2 = (Coordinates)bformatter.Deserialize(mStream);
Console.Write(c2.Coords.Count);
mStream.Close();
}
[TestMethod]
public void TestBinaryWriter()
{
Coordinates c = new Coordinates();
c.SetupTestArray();
MemoryStream mStream = c.RawSerializeToStream();
Console.WriteLine("Length : {0}", mStream.Length);
// Now Deserialize
mStream.Position = 0;
Coordinates c2 = new Coordinates(mStream);
Console.Write(c2.Coords.Count);
}
[TestMethod]
public void TestProtoBufV2()
{
Coordinates c = new Coordinates();
c.SetupTestArray();
MemoryStream mStream = new MemoryStream();
ProtoBuf.Serializer.Serialize(mStream,c);
Console.WriteLine("Length : {0}", mStream.Length);
mStream.Position = 0;
Coordinates c2 = ProtoBuf.Serializer.Deserialize<Coordinates>(mStream);
Console.Write(c2.Coords.Count);
}
}
}
结果(注意PB v2.0.0.423测试版)
Serialize | Ser + Deserialize | Size
-----------------------------------------------------------
BinaryFormatter 2.89s | 26.00s !!! | 21.0 MB
ProtoBuf v2 0.52s | 0.83s | 18.7 MB
Raw BinaryWriter 0.27s | 0.36s | 11.4 MB
显然,这只是考虑速度/大小,没有考虑其他任何因素。
使用BinaryFormatter
的二进制串行化在其生成的字节中包含类型信息。这会占用额外的空间。例如,当您不知道在另一端期望什么样的数据结构时,它很有用。
在您的情况下,您知道数据两端的格式,这听起来不会改变。因此,您可以编写一个简单的编码和解码方法。您的CoOrd类也不再需要可序列化。
我会使用System。IO.BinaryReader和系统。IO.BinaryWriter,然后循环遍历每个CoOrd实例,并将X、Y、Z属性值读/写到流中。假设您的许多数字小于0x7F和0x7FFF,这些类甚至会将您的int压缩到小于11MB。
类似这样的东西:
using (var writer = new BinaryWriter(stream)) {
// write the number of items so we know how many to read out
writer.Write(points.Count);
// write three ints per point
foreach (var point in points) {
writer.Write(point.X);
writer.Write(point.Y);
writer.Write(point.Z);
}
}
从流中读取:
List<CoOrd> points;
using (var reader = new BinaryReader(stream)) {
var count = reader.ReadInt32();
points = new List<CoOrd>(count);
for (int i = 0; i < count; i++) {
var x = reader.ReadInt32();
var y = reader.ReadInt32();
var z = reader.ReadInt32();
points.Add(new CoOrd(x, y, z));
}
}
为了使用预构建序列化程序的简单性,我建议使用protobuf-net;这里是protobuf-netv2,只添加了一些属性:
[DataContract]
public class Coordinates
{
[DataContract]
public struct CoOrd
{
public CoOrd(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
[DataMember(Order = 1)]
int x;
[DataMember(Order = 2)]
int y;
[DataMember(Order = 3)]
int z;
}
[DataMember(Order = 1)]
public List<CoOrd> Coords = new List<CoOrd>();
public void SetupTestArray()
{
Random r = new Random(123456);
List<CoOrd> coordinates = new List<CoOrd>();
for (int i = 0; i < 1000000; i++)
{
Coords.Add(new CoOrd(r.Next(10000), r.Next(10000), r.Next(10000)));
}
}
}
使用:
ProtoBuf.Serializer.Serialize(mStream, c);
以序列化。这需要10960823个字节,但请注意,我调整了SetupTestArray,将大小限制为10000,因为默认情况下,它对整数使用"variant"编码,这取决于大小。10公里在这里并不重要(事实上,我没有检查"步骤"是什么)。如果您喜欢固定尺寸(允许任何范围):
[ProtoMember(1, DataFormat = DataFormat.FixedSize)]
int x;
[ProtoMember(2, DataFormat = DataFormat.FixedSize)]
int y;
[ProtoMember(3, DataFormat = DataFormat.FixedSize)]
int z;
它占用16998640字节