Comparison of several serialization methods in C,

Source: Internet
Author: User

Comparison of several serialization methods in C,

In C #, the comparison only compares the serialization time and the size of the Post-sequential file.

Several types of serialization are:

1. XmlSerializer

2. BinaryFormatter

3. DataContractSerializer

4. DataContractJsonSerializer

5. protobuf-net

The first four types are. Net class libraries, and the last one is Google Protocol Buffers.

First, select an object class as the serialized object and add a serializable dictionary to make the object class slightly more complex.

Code:

    [Serializable]    [ProtoContract]    public class User    {        [ProtoMember(1)]        public int ID { get; set; }        [ProtoMember(2)]        public string Name { get; set; }        [ProtoMember(3)]        public int Age { get; set; }        [ProtoMember(4)]        public SerializableDictionary<Guid, Guid> Dictionary { get; set; }    }    [Serializable]    public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable    {        public void WriteXml(XmlWriter write)       // Serializer        {            var keySerializer = new XmlSerializer(typeof(TKey));            var valueSerializer = new XmlSerializer(typeof(TValue));            foreach (KeyValuePair<TKey, TValue> kv in this)            {                write.WriteStartElement("SerializableDictionary");                write.WriteStartElement("key");                keySerializer.Serialize(write, kv.Key);                write.WriteEndElement();                write.WriteStartElement("value");                valueSerializer.Serialize(write, kv.Value);                write.WriteEndElement();                write.WriteEndElement();            }        }
public void ReadXml(XmlReader reader) // Deserializer { reader.Read(); var keySerializer = new XmlSerializer(typeof(TKey)); var valueSerializer = new XmlSerializer(typeof(TValue)); while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement("SerializableDictionary"); reader.ReadStartElement("key"); TKey tk = (TKey)keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); TValue vl = (TValue)valueSerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadEndElement(); this.Add(tk, vl); reader.MoveToContent(); } reader.ReadEndElement(); } public XmlSchema GetSchema() { return null; } }

Then, initialize a set with 1000 User objects. Each User object contains a dictionary with 500 pairs of guids.

            var list = new List<User>();            var random = new Random();            for (int i = 0; i < 1000; i++)            {                var id = random.Next(0, 10000);                var user = new User                {                    ID = id,                    Name = "Name" + id,                    Age = random.Next(1, 100)                };                var dic = new SerializableDictionary<Guid, Guid>();                for (int j = 0; j < 500; j++)                {                    dic.Add(Guid.NewGuid(), Guid.NewGuid());                }                user.Dictionary = dic;                list.Add(user);            }

Finally, start serialization and use Stopwatch for timing.

1. Xml serialization

Stopwatch sw = new Stopwatch (); // XmlSerializer sw. start (); var xmlSerializer = new XmlSerializer (typeof (List <User>); const string xmlfile = "xml.txt"; var fi = new FileInfo (xmlfile ); using (var stream = fi. create () {xmlSerializer. serialize (stream, list);} sw. stop (); fi. refresh (); Console. writeLine ("XML Time: {0}, Size: {1} K", sw. elapsed, fi. length/1024 );View Code

2. binary serialization

// BinarySerializer sw. restart (); var binarySerializer = new BinaryFormatter (); const string binaryfile = "binary.txt"; var binaryfi = new FileInfo (binaryfile); using (var stream = binaryfi. create () {binarySerializer. serialize (stream, list);} sw. stop (); binaryfi. refresh (); Console. writeLine ("Binary Time: {0}, Size: {1} K", sw. elapsed, binaryfi. length/1024 );View Code

3. DataContractSerializer

// DataContractSerializer sw. restart (); var dataContractSerializer = new DataContractSerializer (typeof (List <User>); const string dataContractfile = "dataContract.txt"; var dataContractfi = new FileInfo (dataContractfile ); using (var stream = dataContractfi. create () {dataContractSerializer. writeObject (stream, list);} sw. stop (); fi. refresh (); Console. writeLine ("DataContrac Time: {0}, Size: {1} K", sw. elapsed, dataContractfi. length/1024 );View Code

4. DataContractJsonSerializer

// DataContractJsonSerializer sw. restart (); var response = new dataContractJsonSerializer (typeof (List <User>); const string dataContractJsonfile = "dataContractJson.txt"; var dataContractJsonfi = new FileInfo (dataContractJsonfile ); using (var stream = dataContractJsonfi. create () {dataContractJsonSerializer. writeObject (stream, list);} sw. stop (); fi. refresh (); Console. writeLine ("DataContractJson Time: {0}, Size: {1} K", sw. elapsed, dataContractJsonfi. length/1024 );View Code

5. protobuf-net

Sw. restart (); // protobuf-net const string protobuffile = "buffer.txt"; var pbfi = new FileInfo (protobuffile); using (var stream = pbfi. create () {Serializer. serialize (stream, list);} sw. stop (); fi. refresh (); Console. writeLine ("Protobuf-net Time: {0}, Size: {1} K", sw. elapsed, pbfi. length/1024 );View Code

I tested it N times in a row and pasted the results three times:

Based on this result, Protobuf-net is superior to other types in terms of serialization speed and serialization volume.

This test is just boring. If there is anything unreasonable, please point it out.


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.