gpt4 book ai didi

c# - 优化多维泛型数组的二进制序列化

转载 作者:太空狗 更新时间:2023-10-29 20:29:41 25 4
gpt4 key购买 nike

我有一个需要二进制序列化的类。该类包含一个字段,如下所示:

private T[,] m_data;

这些多维数组可以相当大(数十万个元素)并且可以是任何原始类型。当我尝试对对象进行标准 .net 序列化时,写入磁盘的文件很大,我认为 .net 存储了大量关于元素类型的重复数据,可能效率不高。

我四处寻找自定义序列化程序,但没有看到任何处理多维通用数组的序列化程序。在序列化并取得一些成功之后,我还在内存流的字节数组上尝试了内置的 .net 压缩,但没有我希望的那么快/压缩。

我的问题是,我应该尝试编写一个自定义序列化程序来针对适当的类型优化序列化此数组(这似乎有点令人生畏),还是应该使用标准 .net 序列化并添加压缩?

任何有关最佳方法的建议,或显示如何处理多维通用数组序列化的资源链接,我们将不胜感激 - 如前所述 existing examples我发现不支持这种结构。

最佳答案

这是我想出的。下面的代码生成一个 int[1000][10000] 并使用 BinaryFormatter 将其写入 2 个文件 - 一个压缩,一个不压缩。

压缩文件为 1.19 MB(1,255,339 字节)解压后为 38.2 MB(40,150,034 字节)

        int width = 1000;
int height = 10000;
List<int[]> list = new List<int[]>();
for (int i = 0; i < height; i++)
{
list.Add(Enumerable.Range(0, width).ToArray());
}
int[][] bazillionInts = list.ToArray();
using (FileStream fsZ = new FileStream("c:\\temp_zipped.txt", FileMode.Create))
using (FileStream fs = new FileStream("c:\\temp_notZipped.txt", FileMode.Create))
using (GZipStream gz = new GZipStream(fsZ, CompressionMode.Compress))
{
BinaryFormatter f = new BinaryFormatter();
f.Serialize(gz, bazillionInts);
f.Serialize(fs, bazillionInts);
}

我想不出更好/更简单的方法来做到这一点。压缩版非常紧。

我会选择 BinaryFormatter + GZipStream。定制一些东西一点也不有趣。


[MG编辑]我希望您不会被编辑冒犯,但是统一重复的 Range(0,width) 极大地扭曲了事情;更改为:

        int width = 1000;
int height = 10000;
Random rand = new Random(123456);
int[,] bazillionInts = new int[width, height];
for(int i = 0 ; i < width;i++)
for (int j = 0; j < height; j++)
{
bazillionInts[i, j] = rand.Next(50000);
}

尝试一下;您会看到 temp_notZipped.txt 为 40MB,temp_zipped.txt 为 62MB。不太吸引人...

关于c# - 优化多维泛型数组的二进制序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/223700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com