F#序列化的歧视性联盟为什么有这么多字节? [英] F# Serialize Discriminated Union why so many bytes?

查看:109
本文介绍了F#序列化的歧视性联盟为什么有这么多字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对于UDP数据包流序列化的一些数据,我得到序列化的巨大开销。如果我的连接codeA的FileData有1K字节数组,我回去2312字节。我将如何减少这方面的开销没有编码和解码的一切我自己?

  [<序列化>]
类型响应=
    |字符串的文件大小*的Int64
    |的Int64的*字节的FileData []
同
    静态成员德code(包:字节[])=
        使用MS =新的MemoryStream(数据包)
        让BF =新的BinaryFormatter()
        bf.Deserialize(毫秒)
        |>拆箱<响应>

    会员this.En code()=
        使用MS =新的MemoryStream()
        让BF =新的BinaryFormatter()
        bf.Serialize(毫秒,这一点)
        ms.GetBuffer()
 

解决方案

BinaryFormatter的可能是最简洁的格式化开箱,所以唯一的办法是自己动手。

你得到的额外开销的原因,是因为有所有保存的序列化的其他信息。串行化并不仅仅保存数据,它也存储的元数据(即:所有类型等)的方式,将整个对象可以安全地重建。这增加了开销。

幸运的是,开销并没有真正的数据变大增加。如果保存了2K字节数组,你可能会回来〜3300字节,而不是〜2300字节 - 因为开销应该是接近恒定(提供的类型信息并没有改变)

I'm trying to serialize some data for a UDP packet stream and I'm getting a huge overhead from serialization. If I encode a FileData with a 1k Byte array I get back 2312 bytes. How would I reduce this overhead without encoding and decoding everything myself?

[<Serializable>]
type Response =
    | FileSize of String * int64
    | FileData of int64 * byte[]
with
    static member Decode(packet : byte[]) =
        use ms = new MemoryStream(packet)
        let bf = new BinaryFormatter()
        bf.Deserialize(ms) 
        |> unbox<Response>

    member this.Encode() =
        use ms = new MemoryStream()
        let bf = new BinaryFormatter()
        bf.Serialize(ms, this)
        ms.GetBuffer()

解决方案

BinaryFormatter is probably the most concise formatter out of the box, so the only option would be to "do it yourself".

The reason you're getting the extra overhead has to do with all of the other information saved with serialization. Serializing doesn't just save the data, it also stores the meta data (ie: all of the types, etc) in a way that the entire object can be reconstructed safely. This adds overhead.

Fortunately, the overhead doesn't really increase as the data gets larger. If you saved a 2k byte array, you'd probably get back ~3300 bytes instead of the ~2300 bytes - since the overhead should be near constant (provided the type information doesn't change).

这篇关于F#序列化的歧视性联盟为什么有这么多字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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