Click here to Skip to main content
15,886,067 members
Articles / Programming Languages / C#

BinaryFormatter vs. Manual Serializing

Rate me:
Please Sign up or sign in to vote.
4.92/5 (13 votes)
13 Jan 2012CPOL6 min read 118.5K   4.3K   25  
Comparison of serializing with BinaryFormatter (standard .NET class) against manual per-byte serializing; some pros and cons before selecting the right method for you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace BinaryFormatterVsManualCoding
{
    class Program
    {
        static byte[] getBytesWithBinaryFormatter(Person toSerialize)
        { 
            MemoryStream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, toSerialize);
            return stream.ToArray();
        }

        static byte[] getBytesWithManualWrite(Person toSerialize)
        {
            MemoryStream stream = new MemoryStream();
            Person.WriteToStream(toSerialize, stream);
            return stream.ToArray();
        }

        static void testSize(Person toTest)
        {
            byte[] fromBinaryFormatter = getBytesWithBinaryFormatter(toTest);
            Console.WriteLine("\tWith binary formatter: {0} bytes", fromBinaryFormatter.Length);
            byte[] fromManualWrite = getBytesWithManualWrite(toTest);
            Console.WriteLine("\tManual serializing: {0} bytes", fromManualWrite.Length);

        }

        static void testTime(Person toTest, int timesToTest)
        {
            List<byte[]> binaryFormatterResultArrays = new List<byte[]>();
            List<byte[]> manualWritingResultArrays = new List<byte[]>();

            DateTime start = DateTime.Now;
            for (int i = 0; i < timesToTest; ++i )
                binaryFormatterResultArrays.Add(getBytesWithBinaryFormatter(toTest));
            TimeSpan binaryFormatterSerializingTime = DateTime.Now - start;

            Console.WriteLine("\tBinary formatter serializing: {0} seconds", binaryFormatterSerializingTime.TotalSeconds);

            start = DateTime.Now;
            for (int i = 0; i < timesToTest; i++)
                manualWritingResultArrays.Add(getBytesWithManualWrite(toTest) );
            TimeSpan manualSerializingTime = DateTime.Now - start;
            
            Console.WriteLine("\tManual serializing: {0} seconds", manualSerializingTime.TotalSeconds);
            BinaryFormatter formatter = new BinaryFormatter();
            start = DateTime.Now;
            foreach (var next in binaryFormatterResultArrays)
                formatter.Deserialize(new MemoryStream(next));
            TimeSpan binaryFormatterDeserializingTime = DateTime.Now - start;

            Console.WriteLine("\tBinaryFormatter desrializing: {0} seconds", binaryFormatterDeserializingTime.TotalSeconds );

            start = DateTime.Now;
            foreach (var next in manualWritingResultArrays)
                Person.ReadFromStream(new MemoryStream(next));
            TimeSpan manualDeserializingTime = DateTime.Now - start;

            Console.WriteLine("\tManual desrializing: {0} seconds", manualDeserializingTime.TotalSeconds );


        }

        static void addCards(Person where, int howMany)
        {
            for (int i = 0; i < howMany; ++i)
            { 
                where.AddNewCard(new CreditCard(Guid.NewGuid().ToString(), new DateTime(2012, 12, 24 )));
            }
        }

        static void Main(string[] args)
        {
            Person aPerson = new Person("Kate", new DateTime(1986, 2, 1), new CreditCard[] { new CreditCard(Guid.NewGuid().ToString(), new DateTime(2012, 12, 24 )) });
            Console.WriteLine("Size test: 1 card");
            testSize(aPerson);
            Console.WriteLine("Time test: 1 card, 100 000 times");
            testTime(aPerson, 100000);

            addCards(aPerson, 10000);
            Console.WriteLine("Size test: 10 000 cards");
            testSize(aPerson);

            Console.WriteLine("Time test: 10 000 cards, 100 times");
            testTime(aPerson, 100);

            Console.ReadKey();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Crypton-M
Ukraine Ukraine
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions