Skip to content

Instantly share code, notes, and snippets.

@dkuppitz
Created June 7, 2013 23:03
Show Gist options
  • Save dkuppitz/5733013 to your computer and use it in GitHub Desktop.
Save dkuppitz/5733013 to your computer and use it in GitHub Desktop.
MsgPack vs. JSON in .NET
Avg. time for JSON serialization: 1 ms
Avg. time for MsgPack serialization: 11 ms
namespace ConsoleApplication5
{
using System;
using System.Diagnostics;
using System.IO;
using MsgPack;
using Newtonsoft.Json;
internal class Program
{
private static void Main()
{
const int loops = 100;
var test = new TestClass
{
Message = "hello world",
Answer = 42,
Time = DateTime.UtcNow
};
var jsonSerializeMillis = MeasureJsonSerialization(test, loops);
var msgpackSerializeMillis = MeasureMsgPackSerialization(test, loops);
Console.WriteLine("Avg. time for JSON serialization: {0} ms", jsonSerializeMillis / loops);
Console.WriteLine("Avg. time for MsgPack serialization: {0} ms", msgpackSerializeMillis / loops);
Console.ReadLine();
}
private static long MeasureJsonSerialization(object obj, int loops)
{
var totalMillis = 0L;
while (loops-- > 0)
{
var sw = Stopwatch.StartNew();
JsonConvert.SerializeObject(obj);
sw.Stop();
totalMillis += sw.ElapsedMilliseconds;
}
return totalMillis;
}
private static long MeasureMsgPackSerialization<T>(T obj, int loops)
{
var totalMillis = 0L;
while (loops-- > 0)
{
var sw = Stopwatch.StartNew();
using (var messageStream = new MemoryStream())
using (var messagePacker = Packer.Create(messageStream))
{
messagePacker.Pack(obj);
}
sw.Stop();
totalMillis += sw.ElapsedMilliseconds;
}
return totalMillis;
}
}
public class TestClass
{
public string Message { get; set; }
public int Answer { get; set; }
public DateTime Time { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment