在下面的代码中,我通过 File 对象的所有 Block 对象并执行基于 BitConverted 的序列化。在某些情况下,我有 OutOfMemory 异常。有什么办法可以优化吗?
File.Serialze();
public byte[] Serialize()
{
byte[] bytes = new byte[Blocks.Count * Block.Size];
for (int i = 0; i < Blocks.Count; i++)
{
Block block = Blocks[i];
Buffer.BlockCopy(block.Serialize(), 0, bytes, i * Block.Size, Block.Size);
}
return bytes;
}
块。序列化()
public byte[] Serialize()
{
byte[] bytes = new byte[Size];
Buffer.BlockCopy(BitConverter.GetBytes(fid), 0, bytes, 0, sizeof(long));
Buffer.BlockCopy(BitConverter.GetBytes(bid), 0, bytes, sizeof(long), sizeof(long));
Buffer.BlockCopy(BitConverter.GetBytes(oid), 0, bytes, sizeof(long) * 2, sizeof(long));
Buffer.BlockCopy(BitConverter.GetBytes(iid), 0, bytes, sizeof(long) * 3, sizeof(long));
Buffer.BlockCopy(BitConverter.GetBytes(did), 0, bytes, sizeof(long) * 4, sizeof(long));
return bytes;
}
MemoryStream 代替 byte[] 和 shift 代替 BitConverter.GetBytes() 方法:
文件.序列化()
public MemoryStream Serialize()
{
MemoryStream fileMemoryStream = new MemoryStream(Blocks.Count * Block.Size);
foreach (Block block in Blocks)
{
using (MemoryStream blockMemoryStream = block.Serialize())
{
blockMemoryStream.WriteTo(fileMemoryStream);
}
}
return fileMemoryStream;
}
块。序列化()
public MemoryStream Serialize()
{
MemoryStream memoryStream = new MemoryStream(Size);
memoryStream.Write(ConvertLongToByteArray(fid), 0, sizeof(long));
memoryStream.Write(ConvertLongToByteArray(bid), 0, sizeof(long));
memoryStream.Write(ConvertLongToByteArray(oid), 0, sizeof(long));
memoryStream.Write(ConvertLongToByteArray(iid), 0, sizeof(long));
memoryStream.Write(ConvertLongToByteArray(did), 0, sizeof(long));
return memoryStream;
}
private byte[] ConvertLongToByteArray(long number)
{
byte[] bytes = new byte[8];
bytes[7] = (byte)((number >> 56) & 0xFF);
bytes[6] = (byte)((number >> 48) & 0xFF);
bytes[5] = (byte)((number >> 40) & 0XFF);
bytes[4] = (byte)((number >> 32) & 0XFF);
bytes[3] = (byte)((number >> 24) & 0xFF);
bytes[2] = (byte)((number >> 16) & 0xFF);
bytes[1] = (byte)((number >> 8) & 0XFF);
bytes[0] = (byte)((number & 0XFF));
return bytes;
}