BinaryFormatter的替代品 [英] BinaryFormatter alternatives

查看:395
本文介绍了BinaryFormatter的替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个128³双精度的BinaryFormatter序列化数组,占用50 MB空间。用两个 double 字段对128³ struct 的数组进行序列化需要150 MB的内存,并且要花费20秒以上的时间来处理。

A BinaryFormatter-serialized array of 128³ doubles, takes up 50 MB of space. Serializing an array of 128³ structs with two double fields takes up 150 MB and over 20 seconds to process.

是否有可以生成紧凑文件的快速简单替代方案?我的期望是上述示例将分别占用16 MB和32 MB,并且处理时间不到两秒钟。我看了一下protobuf-net,但它似乎甚至不支持 struct 数组。

Are there fast simple alternatives that would generate compact files? My expectation is that the above examples would take up 16 and 32 MB, respectively, and under two seconds to process. I took a look at protobuf-net, but it appears that it does not even support struct arrays.

PS:我为制作一个记录文件大小时出错。 BinaryFormatter的实际空间开销并不大。

PS: I apologize for making a mistake in recording file sizes. The actual space overhead with BinaryFormatter is not large.

推荐答案

如果您使用BinaryWriter而不是Serializer,则将获得所需的(最小)。

我不确定速度,但请尝试一下。

If you use a BinaryWriter instead of a Serializer you will get the desired (mimimal) size.
I'm not sure about the speed, but give it a try.

系统写入32MB所需的时间少于0.5秒,包括流的打开和关闭。

On my system writing 32MB takes less than 0.5 seconds, including Open and Close of the stream.

您必须编写自己的 for 循环才能编写数据,像这样:

You will have to write your own for loops to write the data, like this:

struct Pair
{
    public double X, Y;
}

static void WritePairs(string filename, Pair[] data)
{
    using (var fs = System.IO.File.Create(filename))
    using (var bw = new System.IO.BinaryWriter(fs))
    {
        for (int i = 0; i < data.Length; i++)
        {
            bw.Write(data[i].X);
            bw.Write(data[i].Y);
        }
    }
}

static void ReadPairs(string fileName, Pair[] data)
{
    using (var fs = System.IO.File.OpenRead(fileName))
    using (var br = new System.IO.BinaryReader(fs))
    {
        for (int i = 0; i < data.Length; i++)
        {
            data[i].X = br.ReadDouble();
            data[i].Y = br.ReadDouble();
        }
    }
}

这篇关于BinaryFormatter的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆