When the TCP channel is used, the default serializer for. NET remote processing is System. Runtime. Serialization. Formatters. Binary. BinaryFormatter. WCF uses SOAP to send messages, that is, the format is XML. You can set the XML encoding method and select the encoding method as text or binary data. The following test shows which binary stream is generated when the same object is serialized using the BinaryFormatter and the WCF serializer.
Class Program
{
Static void Main (string [] args)
{
Customer customer = new Customer {Age = 30, FirstName = "Gqq", LastName = "Nb "};
Using (FileStream stream1 = new FileStream (@ "B: \ binaryFormatter. bin", FileMode. Create ))
{
BinaryFormatter binFormatter = new BinaryFormatter ();
BinFormatter. Serialize (stream1, customer );
}
Using (FileStream stream2 = new FileStream (@ "B: \ xmlFormatter. bin", FileMode. Create ))
{
Var serializer = new DataContractSerializer (typeof (Customer ));
XmlDictionaryWriter binaryWriter = XmlDictionaryWriter. CreateBinaryWriter (stream2 );
Serializer. WriteObject (binaryWriter, customer );
BinaryWriter. Close ();
}
}
}
[DataContract]
[Serializable]
Class Customer
{
Private string fn;
[DataMember]
Public string FirstName
{
Get {return fn ;}
Set {fn = value ;}
}
Private string ln;
[DataMember]
Public string LastName
{
Get {return ln ;}
Set {ln = value ;}
}
Private int age;
[DataMember]
Public int Age
{
Get {return age ;}
Set {age = value ;}
}
}
In this case, the BinaryFormatter. bin size generated by binaryFormatter is 173 bytes, And the xmlFormatter. bin size generated by XmlDictionaryWriter is 183 bytes. BinaryFormatter wins with a weak advantage.
However, if all attributes in Customer are changed to automatic attributes, the BinaryFormatter. bin generated by binaryFormatter is increased to 237 bytes, And the xmlFormatter. bin size generated by XmlDictionaryWriter remains unchanged. This is because BinaryFormatter records the names and values of the backup fields. When automatic attribute is used, the backup field of FirstName is <firstname> k _ BackingField, which is long.
Therefore, I think BinaryFormatter and XmlDictionaryWriter can serialize the same object to produce the same file length. As for the time required for serialization, the time required for data transmission over the network should be negligible and will not be tested.
Column of the author gqqnb