Created
March 31, 2009 21:34
-
-
Save anonymous/88422 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
using System.Linq; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Runtime.Serialization.Formatters.Binary; | |
namespace ISerializable { | |
class Program { | |
[Serializable] | |
class NumberObject { | |
public int Number { get; set; } | |
} | |
static int indent = 0; | |
static void TimeAction(string description, Action func) { | |
var watch = new Stopwatch(); | |
watch.Start(); | |
func(); | |
watch.Stop(); | |
Console.WriteLine("Time Elapsed {0} ms", watch.ElapsedMilliseconds); | |
Console.WriteLine(description); | |
} | |
static void Main(string[] args) { | |
var rand = new Random(); | |
var numbers = Enumerable.Range(0, 100000) | |
.Select(x => rand.Next()).ToArray(); | |
TimeAction("Full Serialization Cycle: Builtin Int[100000]", () => | |
{ | |
var stream = new MemoryStream(); | |
var formatter = new BinaryFormatter(); | |
formatter.Serialize(stream, numbers); | |
stream.Position = 0; | |
numbers = (int[])formatter.Deserialize(stream); | |
}); | |
var numberObjects = numbers.Select(i => new NumberObject() { Number = i }).ToArray(); | |
TimeAction("Full Serialization Cycle: NumberObject[100000]", () => | |
{ | |
var stream = new MemoryStream(); | |
var formatter = new BinaryFormatter(); | |
formatter.Serialize(stream, numberObjects); | |
stream.Position = 0; | |
numberObjects = (NumberObject[])formatter.Deserialize(stream); | |
}); | |
TimeAction("Full Serialization Cycle: Manual NumberObject[100000]", () => | |
{ | |
var stream = new MemoryStream(); | |
var formatter = new BinaryFormatter(); | |
var writer = new BinaryWriter(stream); | |
writer.Write(numberObjects.Length); | |
foreach (var numberObject in numberObjects) { | |
writer.Write(numberObject.Number); | |
} | |
stream.Position = 0; | |
var reader = new BinaryReader(stream); | |
var count = reader.ReadInt32(); | |
numberObjects = new NumberObject[count]; | |
for (int i = 0; i < numberObjects.Length; i++) { | |
numberObjects[i] = new NumberObject() { Number = reader.ReadInt32()}; | |
} | |
}); | |
Console.ReadKey(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment