Пример #1
0
        private static void Test()
        {
            SerializableClass targetObj = new SerializableClass();
            Type t = typeof(SerializableClass);

            string filePath = @"d:\tmp\";

            BinaryFormatter binaryFormatter = new BinaryFormatter();
            DataContractSerializer xmlSerializer = new DataContractSerializer(t);
            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(t);

            Stopwatch sw = new Stopwatch();

            // DataContractSerializer
            using (Stream stream = File.OpenWrite(filePath + xmlSerializer.GetType())) {
                sw.Start();
                xmlSerializer.WriteObject(stream, targetObj);
                sw.Stop();

                Console.WriteLine(xmlSerializer.GetType().Name + "\t\tシリアライズ\t" + sw.Elapsed);
                sw.Reset();
            }

            using (Stream stream = File.OpenRead(filePath + xmlSerializer.GetType())) {
                sw.Start();
                xmlSerializer.ReadObject(stream);
                sw.Stop();

                Console.WriteLine(xmlSerializer.GetType().Name + "\t\tデシリアライズ\t" + sw.Elapsed);
                sw.Reset();
            }

            // DataContractJsonSerializer
            using (Stream stream = File.OpenWrite(filePath + jsonSerializer.GetType())) {
                sw.Start();
                jsonSerializer.WriteObject(stream, targetObj);
                sw.Stop();

                Console.WriteLine(jsonSerializer.GetType().Name + "\tシリアライズ\t" + sw.Elapsed);
                sw.Reset();
            }

            using (Stream stream = File.OpenRead(filePath + jsonSerializer.GetType())) {
                sw.Start();
                jsonSerializer.ReadObject(stream);
                sw.Stop();

                Console.WriteLine(jsonSerializer.GetType().Name + "\tデシリアライズ\t" + sw.Elapsed);
                sw.Reset();
            }

            // BinaryFormatter
            using (Stream stream = File.OpenWrite(filePath + binaryFormatter.GetType())) {
                sw.Start();
                binaryFormatter.Serialize(stream, targetObj);
                sw.Stop();

                Console.WriteLine(binaryFormatter.GetType().Name + "\t\t\tシリアライズ\t" + sw.Elapsed);
                sw.Reset();
            }

            using (Stream stream = File.OpenRead(filePath + binaryFormatter.GetType())) {
                sw.Start();
                binaryFormatter.Deserialize(stream);
                sw.Stop();

                Console.WriteLine(binaryFormatter.GetType().Name + "\t\t\tデシリアライズ\t" + sw.Elapsed);
                sw.Reset();
            }
        }