BinaryFormatter alternatives

前端 未结 3 2266
旧巷少年郎
旧巷少年郎 2020-12-30 04:37

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 an

3条回答
  •  清酒与你
    2020-12-30 04:44

    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.

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

    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();
            }
        }
    }
    

提交回复
热议问题