Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Reflection;
- using System.Runtime.Serialization.Formatters.Binary;
- namespace SerializeVsReflect
- {
- [Serializable]
- public class Person
- {
- public int Id;
- public string FirstName;
- public string LastName;
- public int Age;
- public decimal Weight;
- }
- class Program
- {
- static void Main(string[] args)
- {
- var person = new Person();
- person.Id = 10;
- person.Age = 31;
- person.FirstName = "James";
- person.LastName = "Stuart";
- person.Weight = 79;
- int iterations = 200000;
- var serializationMs = Serialization(person, iterations);
- var reflectionMs = Reflection(person, iterations);
- string resultMessageFormat = "{0}, {1} iterations: {2} ms";
- Console.WriteLine(resultMessageFormat, "BinaryFormatter", iterations, serializationMs);
- Console.WriteLine(resultMessageFormat, "Reflection", iterations, reflectionMs);
- Console.WriteLine("Done");
- Console.ReadLine();
- }
- private static long Serialization(Person person, int iterations)
- {
- var stopwatch = new Stopwatch();
- using (var stream = new MemoryStream())
- {
- var formatter = new BinaryFormatter();
- stopwatch.Start();
- for (int i = 0; i < iterations; i++)
- {
- formatter.Serialize(stream, person);
- stream.Seek(0, SeekOrigin.Begin);
- var deserialized = (Person)formatter.Deserialize(stream);
- }
- stopwatch.Stop();
- return stopwatch.ElapsedMilliseconds;
- }
- }
- private static long Reflection(Person person, int iterations)
- {
- var stopwatch = new Stopwatch();
- stopwatch.Start();
- for (int i = 0; i < iterations; i++)
- {
- var newPerson = Activator.CreateInstance<Person>();
- var fields = newPerson.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
- foreach (var field in fields)
- {
- var value = field.GetValue(person);
- field.SetValue(newPerson, value);
- }
- }
- stopwatch.Stop();
- return stopwatch.ElapsedMilliseconds;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement