Juval Lowyさん書の、Programming .NET Componentsという本を読んでいてBinaryFormatterを使用したオブジェクトのシリアライズ方法に出くわした。そこで調べたくなったのが、作成されたファイルのサイズとシリアライズされる早さでした。


私が書いた簡単なサンプルではXMLのファイルサイズが14kbのところが、BinaryFormatterを使ってシリアライズすると6kbになりました。スピードはなんとBinaryFormatterを使用した方が19倍も早かったです。下にそのコードの例を載せておきます。もし何か気が付いたことがあったら教えてくださいませ。


using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.Serialization.Formatters.Binary;

using System.IO;

using System.Xml.Serialization;



namespace BinarySerialization

{

class Program

{

[System.Runtime.InteropServices.DllImport("KERNEL32")]

private static extern bool QueryPerformanceCounter(ref long lpPerformanceCount);

[System.Runtime.InteropServices.DllImport("KERNEL32")]

private static extern bool QueryPerformanceFrequency(ref long lpFrequency);



static void Main(string[] args)

{

long frequency = 0;

QueryPerformanceFrequency(ref frequency);



long startTime = 0;

QueryPerformanceCounter(ref startTime);



RunTest();



long endTime = 0;

QueryPerformanceCounter(ref endTime);



float elapsed = (float)(endTime - startTime) / frequency;



Console.WriteLine(“{0:0000.000}ms “, elapsed);

Console.ReadLine();

}



private static void RunTest()

{

Serialize(SerializationType.Binary);

}



private static void Serialize(SerializationType serializationType)

{

List<Customer> Customers = new List<Customer>();



for (int i = 0; i < 1000; i++)

{

Customer c = new Customer();

c.CustomerID = i;

c.FirstName = “FirstName” + i.ToString();

c.LastName = “LastName” + i.ToString();



Customers.Add(c);

}



string strFilePath = serializationType == SerializationType.Binary ? @”C:\Temp\obj.bin” : @”C:\Temp\obj.xml”;

Stream stream = new FileStream(strFilePath, FileMode.Create, FileAccess.Write);



switch (serializationType)

{

case SerializationType.Xml:

XmlSerializer serializer = new XmlSerializer(Customers.GetType());

serializer.Serialize(stream, Customers);

stream.Close();

break;

case SerializationType.Binary:

BinaryFormatter formatter = new BinaryFormatter();

formatter.Serialize(stream, Customers);

stream.Close();

break;

}

}



private enum SerializationType

{

Binary,

Xml

}

}

}

コメント書き込み