Why is binary serialization faster than xml serialization?

前端 未结 5 1411
无人共我
无人共我 2021-02-19 20:46

Why is binary serialization considered faster than xml serialization?

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 21:16

    Actually, like all things - it depends on the data, and the serializer.

    Commonly (although perhaps unwisely) people mean BinaryFormatter for "binary", but this has a number of foibles:

    • in adds lots of type metadata (which all takes space)
    • by default it includes field names (which can be verbose, especially for automatically implemented properties)

    Conversely, xml generally has overheads such as:

    • tags adding space and IO
    • the need to parse tags (which is remarkably expensive)
    • lots of text encoding/decoding

    Of course, xml is easily compressed, adding CPU but hugely reducing bandwidth.

    But that doesn't mean one is faster; I would refer you to some sample stats from here (with full source included), to which I've annotated the serializer base (binary, xml, text, etc). Look in particular at the first two results; it looks like XmlSerializer trumped BinaryFormatter on every value, while retaining the cross-platform advantages. Of course, protobuf then trumps XmlSerializer ;p

    These numbers tie in quite well to ServiceStack's benchmarks, here.

    BinaryFormatter *** binary
    Length: 1314
    Serialize: 6746
    Deserialize: 6268
    
    XmlSerializer *** xml
    Length: 1049
    Serialize: 3282
    Deserialize: 5132
    
    DataContractSerializer *** xml
    Length: 911
    Serialize: 1411
    Deserialize: 4380
    
    NetDataContractSerializer *** binary
    Length: 1139
    Serialize: 2014
    Deserialize: 5645
    
    JavaScriptSerializer *** text (json)
    Length: 528
    Serialize: 12050
    Deserialize: 30558
    
    (protobuf-net v2) *** binary
    Length: 112
    Serialize: 217
    Deserialize: 250
    

提交回复
热议问题