对于其他遇到这个问题的人,如果你只需要小端序并且不需要自动检测大端序并从中转换,那么我已经编写了一个扩展版本的BitConverter,其中包含许多添加项来处理Span以及转换类型为T的数组,例如int[]或timestamp[]。
还扩展了支持的类型,包括时间戳、十进制和日期时间。
https://github.com/tcwicks/ChillX/blob/master/src/ChillX.Serialization/BitConverterExtended.cs
使用示例:
Random rnd = new Random();
RentedBuffer<byte> buffer = RentedBuffer<byte>.Shared.Rent(BitConverterExtended.SizeOfUInt64
+ (20 * BitConverterExtended.SizeOfUInt16)
+ (20 * BitConverterExtended.SizeOfTimeSpan)
+ (10 * BitConverterExtended.SizeOfSingle);
UInt64 exampleLong = long.MaxValue;
int startIndex = 0;
startIndex += BitConverterExtended.GetBytes(exampleLong, buffer.BufferSpan, startIndex);
UInt16[] shortArray = new UInt16[20];
for (int I = 0; I < shortArray.Length; I++) { shortArray[I] = (ushort)rnd.Next(0, UInt16.MaxValue); }
startIndex += BitConverterExtended.GetBytesUShortArray(shortArray, buffer.BufferSpan, startIndex);
TimeSpan[] timespanArray = new TimeSpan[20];
for (int I = 0; I < timespanArray.Length; I++) { timespanArray[I] = TimeSpan.FromSeconds(rnd.Next(0, int.MaxValue)); }
startIndex += BitConverterExtended.GetBytes(timespanArray, buffer.BufferSpan, startIndex);
float[] floatArray = new float[10];
for (int I = 0; I < floatArray.Length; I++) { floatArray[I] = MathF.PI * rnd.Next(short.MinValue, short.MaxValue); }
startIndex += BitConverterExtended.GetBytes(floatArray, buffer.BufferSpan, startIndex);
buffer.Return();
buffer = null;
它支持从byte[]或RentedBuffer读取和写入,但使用RentedBuffer类可以大大减少GC收集开销。
RentedBufferContract类在内部处理返回缓冲区到池中以防止内存泄漏。
还包括一个类似于MessagePack的序列化器。
注意:MessagePack是一种更快速、更具特色的序列化器,但此序列化器通过从租用的字节缓冲区读取和写入来减少GC收集开销。
https://github.com/tcwicks/ChillX/blob/master/src/ChillX.Serialization/ChillXSerializer.cs