C#, ConcurrentDictionary.GetOrAdd – Func not exclusively accessed

This is a quick post showing you the behavior of ConcurrentDictionary.GetOrAdd, which might not be what you expect. I bet that when you first read it, you think:

If the key exists, the corresponding value is returned; if not the Func is executed “Once”, and the resulting value is associated with the key.

Are you sure about this? Lets have a look. The code below kicks of two tasks that will access GetOrAdd for the same key. I use some threading synchronization techniques to get concurrent execution of the Func. Like: SemaphoreSlim, SpinWait, Interlocked.Increment.

private static readonly StringBuilder Log = new StringBuilder();
private static readonly SemaphoreSlim Sync = new SemaphoreSlim(1, 1);
private static int _tasksStartedCount = 0;

static void Main(string[] args)
{
	var dictionary = new ConcurrentDictionary<int, string>();
	var key = 42;

	//Semaphore is used to control the flow of the tasks.
	Sync.Wait();
		
	var task1 = Task.Factory.StartNew(() =>
	{
		Thread.CurrentThread.Name = "Task1's thread";
		dictionary.GetOrAdd(key, CreateItem);
	});
	Log.AppendLine("Started Task1");

	var task2 = Task.Factory.StartNew(() =>
	{
		Thread.CurrentThread.Name = "Task2's thread";
		dictionary.GetOrAdd(key, CreateItem);
	});
	Log.AppendLine("Started Task2");

	//Wait until both tasks are waiting to return factory value
	var spinWait = new SpinWait();
	while (_tasksStartedCount < 2)
		spinWait.SpinOnce();

	Log.AppendLine("Main - Releasing Sync so that tasks can proceed");
	Sync.Release();

	Task.WaitAll(task1, task2);
	Log.AppendLine("Tasks done");

	Console.WriteLine(Log.ToString());
	Console.WriteLine("Dictionary contains string: '{0}'", 
            dictionary.First().Value);

	Console.ReadKey();
}

private static string CreateItem(int key)
{
	try
	{
		//Increase value so that Sync in Main will be released
		Interlocked.Increment(ref _tasksStartedCount);

		Log.AppendFormat("Thread '{0}' - In CreateItem, before Sync.Wait\r\n", 
                    Thread.CurrentThread.Name);
		Sync.Wait();
		Log.AppendFormat("Thread '{0}' - In CreateItem, returning value: '{0}'.\r\n", 
                    Thread.CurrentThread.Name);
			
		return Thread.CurrentThread.Name;
	}
	finally
	{
		Log.AppendFormat("Thread '{0}' - In CreateItem, before Sync.Release\r\n", 
                    Thread.CurrentThread.Name);
		Sync.Release();
		Log.AppendFormat("Thread '{0}' - In CreateItem, after Sync.Release\r\n", 
                    Thread.CurrentThread.Name);
	}
}

The output of this (with some variances) is:

Note that BOTH Funcs where executed but the first one finished was used for the value. Hence, if you pass a factory, don’t make it expensive. You could of course use it in conjunction with e.g. Lazy, that is, let the Dictionary hold a value of Lazy of T.

//Daniel

C#, Consuming anonymous types at a later point

Last night I was dealing with anonymous types and some IL code to creating and assigning values to instances of anonymous types. I stumbled upon this question:

How do I declare a Field with Anonymous Type (C#)

- http://stackoverflow.com/questions/964334/how-do-i-declare-a-field-with-anonymous-type-c

It didn’t have anything to do with what I was doing but the thing I was doing would solve the issue. I was bringing anonymous types support to ServiceStack.Text, the .Net communities most awesome Serialization framework. Yes I know that the feature already exists in JSON.Net, but when it comes to serialization, I want speed, hence why I turn to ServiceStack.

Alternative 1 – Lets solve the problem using JSON

Step 1 – Install ServiceStack.Text v3.3.6 or later

This feature was introduced in v3.3.6, so use that NuGet.

install-package ServiceStack.Text

Step 2 – Get some data

For this simple demo I will just use some simple person entities that gets yielded.

public class Person
{
	public string Firstname { get; set; }
	public string Lastname { get; set; }
	public int Age { get; set; }
}

public static class Db
{
	public static IEnumerable<Person> Persons()
	{
		yield return new Person
		{
			Firstname = "Hans",
			Lastname = "Wertheim", 
			Age = 30
		};
		yield return new Person
		{
			Firstname = "Daniel", 
			Lastname = "Wertheim", 
			Age = 31
		};
		yield return new Person
		{
			Firstname = "Anton",
			Lastname = "Wertheim", 
			Age = 32
		};
	}
}

Step 3 – Turn it into JSON

Now we need the state turned into JSON. If we want we could transform the data now. Lets combine Firstname and Lastname to Name.

var personsAsJson = Db.Persons()
	.Select(p => new
	{
		p.Age, 
		Name = string.Concat(p.Firstname, " ", p.Lastname)
	})
	.Select(JsonSerializer.SerializeToString)
	.ToArray();

Step 4 – Define a extension method for deserialization

Once we have the JSON blob, we need a deserialization method allowing us to define a anonymous type, used as a template.

public static IEnumerable<T> ToAnonymousType<T>(
	this IEnumerable<string> json, T template) where T : class
{
	TypeConfig<T>.EnableAnonymousFieldSetters = true;
	var templateType = template.GetType();
	return json.Select(j => JsonSerializer.DeserializeFromString(j, templateType) as T);
}

Step 5 – Consume it as we want in another domain

Now, in another domain we could just turn it into a anonymous type of our like. E.g only picking out Name.

var anonymousPersons = personsAsJson.ToAnonymousType(new {Name = default(string)});

foreach (var anonymousPerson in anonymousPersons)
	Console.WriteLine(anonymousPerson.Name);

That’s it. No classes (other than anonymous) used in the tranformations what so ever. Not saying you should, just saying you could.

//Daniel

C#, Why params object[] should be forbidden! (v2)

Edit: This post has been rewritten since I first wrote it. I wrote the first edition in frustration and wasn’t to clear on my point.

Lets start with a sample. First we have a method accepting an int[], using the params keyword. It just tries to output them.

static void Dump1(params int[] ids)
{
	foreach (var id in ids)
		Console.WriteLine(id);
}

Lets consume it

Dump1(1,2,3);
//Outputs
//1
//2
//3

Dump1(new[] { 1, 2, 3 });
//Outputs
//1
//2
//3

Fine. Just what we wanted. The first call passes three values and the second call passes three values, right? No. The last call passes “one” array with three values. But since the Dump1 method accepts params int[], it works.

Now, lets screw things up. Switch params int[] to params object[] and run the same test cases again.

static void Dump2(params object[] ids)
{
	foreach (var id in ids)
		Console.WriteLine(id);
}
Dump2(1,2,3);
//Outputs
//1
//2
//3

Dump2(new[] { 1, 2, 3 });
//Outputs
//System.Int32[]

System.Int32[]

I guess System.Int32 isn’t exactly what you first expect when writing a method like Dump2. Yes, I know there should have been a failing test, but there wasn’t. But there’s a completly other semantic meaning behind passing an int[] array to an params int[] vs to an params object[] array. Of course it shouldn’t be forbidden, that’s a strong word. But it should at least (per default) generate a squiggle in ReSharper ;-)

Now lets finnish with a small tweak. I’ve added a simple recursive extension method. Now we can pass values as we want.

static void Dump(params object[] ids)
{
	foreach (var id in ids.Yield()) //Calling extensionmethod
		Console.WriteLine(id);
}

public static class Extensions
{
	public static IEnumerable<object> Yield(this IEnumerable items)
	{
		if(items == null)
			yield break;

		foreach (var item in items)
		{
			if (item is IEnumerable)
				foreach (var o in Yield(item as IEnumerable))
					yield return o;
			else
				yield return item;
		}
	}
}
Dump(1, 2, 3);
//Outputs
//1
//2
//3

Dump(new[] { 1, 2, 3 });
//Outputs
//1
//2
//3

Dump(new List<int> { 1, 2, 3 });
//Outputs
//1
//2
//3

Dump(new List<int> { 1, 2, 3 });
//Outputs
//1
//2
//3

Dump(1, new[] { 2, 3 }, new[] { new[] { 4, 5 }, new[] { 6, 7 } });
//Outputs
//1
//2
//3
//4
//5
//6
//7

As I said. Off course it should not be forbidden. But, I urge you to think how it will behave when you use params object[].

//Daniel

C#, Parallel deserialization of JSON stored in database

The scenario

A while back ago I had to yield entities constructed by deserializing JSON stored in a database. The first solution just opened a simple single result, sequential reader against the database returning a one column result set containing JSON. This was just yield returned after deserialized to the desired entity. Trying to tweak this I turned to the task parallel library. The idea was to in a separate task, read from the datareader and at the same time in, the main thread, deserialize the JSON string and yield entities while still reading from the database.

The solution

First, lets be clear. I’m not saying you should see this as an solution that fits in all similar scenarios. In my case it was faster reading the strings from the database then doing the deserialization, but it wasn’t to big of a difference, hence there wasn’t that much more memory consumption caused by a large BlockingCollection. But this is something you have to test and measure for your needs. But everything depends on the scenarios. How big is the JSON string? How many items are there? How’s the infrastructure? But lets put that aside and have a look at the solution. The sourceData below comes from yielding the datareader. In a separate task I read from a datareader which represent a single column result set with a string, a JSON. In that task I add the JSON string to a BlockingCollection that wraps the ConcurrentQueue. At the same time in the main thread I TryTake/dequeue a JSON string from the collection and then yield return it deserialized.

When the reading from the database is done, the task is closed and I then deserialize all the non deserialized JSON strings.

public IEnumerable<T> DeserializeManyInParallel<T>(IEnumerable<string> sourceData) where T : class
{
	using (var q = new BlockingCollection<string>())
	{
		Task task = null;

		try
		{
			task = new Task(() =>
			{
				foreach (var json in sourceData)
					q.Add(json);

				q.CompleteAdding();
			});

			task.Start();

			foreach (var e in q.GetConsumingEnumerable())
				yield return JsonSerializer.DeserializeFromString<T>(e);
		}
		finally
		{
			if (task != null)
			{
				Task.WaitAll(task);
				task.Dispose();
			}

			q.CompleteAdding();
		}
	}
}

Again! Measure, test and try it for your scenarios, before accepting it as a solution.

//Daniel

C#, Visual Studio 2010, No more Client profile in 5minutes.

I guess I’m not alone being tired of running into the “Client profile” framework version used when creating a Console application in Visual Studio 2010. Don’t know how life is going to be in coming version of Visual Studio, but until then, lets show you a solution that takes no more than 5 minutes.

Step 1 – Locate the Project template shipped with Visual Studio

For me the installation set this up here: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ProjectTemplates\CSharp\Windows\1033

Step 2 – Edit the VS-Template file

Unzip the content of ConsoleApplication.zip to a temp location. Rename csConsoleApplication.vstemplate to csConsoleApplication-NoClientProfile.vstemplate. Open the file with a plain old text editor and make the following change. More info: http://msdn.microsoft.com/en-us/library/ms185291.aspx

Original

<?xml version="1.0" encoding="utf-8"?>
<VSTemplate Version="3.0.0" Type="Project" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2320" />
    <Description Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="2321" />
    <Icon Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="4548" />
    <TemplateID>Microsoft.CSharp.ConsoleApplication</TemplateID>
    <ProjectType>CSharp</ProjectType>
    <RequiredFrameworkVersion>2.0</RequiredFrameworkVersion>
    <SortOrder>12</SortOrder>
    <NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>ConsoleApplication</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
  </TemplateData>
  <TemplateContent>
    <Project File="ConsoleApplication.csproj" ReplaceParameters="true">
      <ProjectItem ReplaceParameters="true" TargetFileName="Properties\AssemblyInfo.cs">AssemblyInfo.cs</ProjectItem>
      <ProjectItem ReplaceParameters="true" OpenInEditor="true">Program.cs</ProjectItem>
      <ProjectItem ReplaceParameters="true">App.config</ProjectItem>
    </Project>
  </TemplateContent>
</VSTemplate>

Change this
Provide new tags for:

<Name>
<Description>

Remove the tag:

<TemplateId>

Updated

<?xml version="1.0" encoding="utf-8"?>
<VSTemplate Version="3.0.0" Type="Project" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>ConsoleApplication-NoClientProfile</Name>
    <Description>Ordinary Console application but NO CLIENT PROFILE</Description>
    <Icon Package="{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}" ID="4548" />
    <ProjectType>CSharp</ProjectType>
    <RequiredFrameworkVersion>2.0</RequiredFrameworkVersion>
    <SortOrder>12</SortOrder>
    <NumberOfParentCategoriesToRollUp>1</NumberOfParentCategoriesToRollUp>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>ConsoleApplication</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
  </TemplateData>
  <TemplateContent>
    <Project File="ConsoleApplication.csproj" ReplaceParameters="true">
      <ProjectItem ReplaceParameters="true" TargetFileName="Properties\AssemblyInfo.cs">AssemblyInfo.cs</ProjectItem>
      <ProjectItem ReplaceParameters="true" OpenInEditor="true">Program.cs</ProjectItem>
      <ProjectItem ReplaceParameters="true">App.config</ProjectItem>
    </Project>
  </TemplateContent>
</VSTemplate>

Step 3 – Edit the CS-project file

Locate this section:

$if$ ($targetframeworkversion$ >= 4.0)
  <TargetFrameworkProfile>Client</TargetFrameworkProfile>
$endif$

and remove Client.

$if$ ($targetframeworkversion$ >= 4.0)
  <TargetFrameworkProfile></TargetFrameworkProfile>
$endif$

Step 4 – Zip and “install” the new template

Rezip the extracted files from Step 2 into a new file ConsoleApplication-NoClientProfile.zip and drop it into the folder that holds custom project templates for Visual Studio. For me this was: C:\Users\sedanwer\Documents\Visual Studio 2010\Templates\ProjectTemplates\Visual C#

More info: http://msdn.microsoft.com/en-us/library/y3kkate1.aspx

Step 5 – Consume it

The next time you start Visual Studio 2010 and do File – New project, you will now find your now project template under CSharp – Windows.

That’s it. Have fun!

//Daniel

C#, Generic factory with support for private constructors

Today I got involved in a small question on Twitter on how to create a generic factory creating instances of classes having a private constructor. So I put together a small sample that shows a two solutions:

  • Using Activator (around 22s per 100000)
  • Using compiled lambdas (around 8s per 100000)

The example lets you time the difference between the solutions. And feel free to add the code using IL. Please note! This was something I put together really quick so there’s probably some room left for you to tweak.

The source code is also made availible as a Gist here: https://gist.github.com/1529618

Sample model

public interface IPerson
{
	string Name { get; set; }
}

public class Person : IPerson 
{
	public string Name { get; set; }

	private Person() { }
}

The factory

public static class Factory<T> where T : class 
{
	private static readonly Func<T> FactoryFn;

	static Factory()
	{
		//FactoryFn = CreateUsingActivator();

		FactoryFn = CreateUsingLambdas();
	}

	private static Func<T> CreateUsingActivator()
	{
		var type = typeof(T);

		Func<T> f = () => Activator.CreateInstance(type, true) as T;

		return f;
	}

	private static Func<T> CreateUsingLambdas()
	{
		var type = typeof(T);

		var ctor = type.GetConstructor(
			BindingFlags.Instance | BindingFlags.CreateInstance |
			BindingFlags.NonPublic,
			null, new Type[] { }, null);

		var ctorExpression = Expression.New(ctor);
		return Expression.Lambda<Func<T>>(ctorExpression).Compile();
	}

	public static T Create(Action<T> init)
	{
		var instance = FactoryFn();

		init(instance);

		return instance;
	}
}

The test app

class Program
{
    static void Main(string[] args)
    {
		//TOUCH ONCE BEFORE TIMING
		var touchedPerson = Factory<Person>.Create(p => p.Name = "Daniel");

		for (var a = 0; a < 5; a++)
		{
			var sw = Stopwatch.StartNew();
			for (int c = 0; c < 100000; c++)
			{
				var person = Factory<Person>.Create(p => p.Name = "Daniel");
				var n = person.Name;
			}
			sw.Stop();
			Console.WriteLine(sw.Elapsed.TotalMilliseconds);
		}
		Console.ReadKey();
    }
}

That’s it. Enjoy!

//Daniel

Ensure.That – a simple guard clause project

Yes I know there’s a bunch of these projects out there already and that there’s built in support for using code-contracts in .Net, but even so we found a need for a custom API, hence Ensure.That was created. Also, I think Microsoft’s Code-contracts fails on the part of having to install an add-on to VS2010 to actually put the Code-contract requirements to use. Until it’s a first class citizen of VS, it’s not useful in my eyes. Enough about that.

Why

Easy, to provide a clean API for validating arguments and a solution that throws natural argument exceptions with informative exception messages.

NuGet

It’s distributed using NuGet. You could consume it as a normal lib or as a source distribution. The later gives you the possibility of incorporating it into any existing “common core lib” that you already use for these kind of utils.

Some code

The API is continuously evolving and it hasn’t reached v1.0 yet, hence there might be braking changes, but that’s not very likely. There will probably only be new stuff added.

Without parametername

Will throw ArgumentNullException or ArgumentException without ParameterName.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(myString).IsNotNullOrEmpty();
    Ensure.That(myInt).IsInRange(10, 20);
    Ensure.That(myGuid).IsNotEmpty();
}

Using Lambdas

Note, that since the value also is extracted via the Lambda there’s a compile of it, hence the other overloads or more performant.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(() => myString).IsNotNullOrEmpty();
    Ensure.That(() => myInt).IsInRange(10, 20);
    Ensure.That(() => myGuid).IsNotEmpty();
}

Providing parameter name explicitly

Will work as the first example with the difference of including the parameter name in the exception’s _ParameterName _property.

public void MyMethod(string myString, int myInt, Guid myGuid)
{
    Ensure.That(myString, "myString").IsNotNullOrEmpty();
    Ensure.That(myInt, "myInt").IsInRange(10, 20);
    Ensure.That(myGuid, "myGuid").IsNotEmpty();
}

More information and sourcecode is available on the GitHub site.

//Daniel

C# – Building a dynamic method recorder using DynamicObject

Was at an OpenSpace event today in Stockholm. Was really great. Lots of inspiring discussions. Was in a discussion about Ruby/IronRuby and C# where there was this case where a methodcall recorder was built with a few lines in Ruby and that it wasn’t doable that easy in C#. Well, I kind of disagree and took up my laptop and put together a few lines (a bit rough) since I just wanted to check if it was doable. The resulting code is below, and yes it is possible.

The case: Create an class that you can invoke methods on dynamically and then replay those calls on another class with the same API.

Note, that the code below isn’t optimized but just a proof of concept

You could probably also remove the reflection and use a binder to invoke the method, but I don’t know. As I said just a proof of concept.

Calling code

static void Main(string[] args)
{
    //Record some calls
    dynamic dyn = new Recorder();
    dyn.Write("Daniel");
    dyn.WriteLine(" Wertheim");
    dyn.WriteLine("building a");

	//
    dyn.PlayBackOn(new Writer());
}

The recorder

public class Recorder : DynamicObject
{
    private readonly Queue<KeyValuePair<string, object[]>> _calls
        = new Queue<KeyValuePair<string, object[]>>();

    public override bool TryInvokeMember(
        InvokeMemberBinder binder, object[] args, out object result)
    {
        _calls.Enqueue(new KeyValuePair<string, object[]>(binder.Name, args));
        result = null;
        return true;
    }

    public void PlayBackOn<T>(T item)
    {
        var t = typeof(T);

        while(_calls.Count > 0)
        {
            var kv = _calls.Dequeue();
            t.GetMethod(kv.Key).Invoke(item, kv.Value);   
        }
    }
}

The object being played

public class Writer
{
    public void Write(string arg)
    {
        Console.Write(arg);
    }

    public void WriteLine(string arg)
    {
        Console.WriteLine(arg);
    }
}

As always, have fun.

//Daniel @@danielwertheim

Json.Net vs ServiceStack.Text

This is going to be a verry short comparision of the two Json-serialization frameworks:
Json.Net – http://json.codeplex.com
ServiceStack.Text – https://github.com/mythz/ServiceStack.Text

I have always used Json.Net when dealing with serialization of entities back and forth to Json, but then I stumbled upon this: “Fastest JSON Serializer for .NET released” – http://www.servicestack.net/mythz_blog/?p=344 Man was I excited, since I need the “best” performance I can get for this in SisoDb (http://www.sisodb.com)

Lets do a simple test

I just downloaded latest version of both libraries (Json.Net – changeset: 57577), (ServiceStack.Text – changeset: c3e5d0c, v1.8), compiled them for .Net 4.0 Client profile and put together a very simple example. Note, I’m not testing features here, just raw serialization and deserialization. I don’t know if you can “tweak” ServiceStack.Text as much as you can with Json.Net, e.g: Strategies for null property handling, missing member, indentation of Json etc.

Item being serialized

[Serializable]
public class Customer
{
    public int Id { get; set; }

    public int CustomerNo { get; set; }

    public string Firstname { get; set; }

    public string Lastname { get; set; }

    public ShoppingIndexes ShoppingIndex { get; set; }

    public DateTime CustomerSince { get; set; }

    public Address BillingAddress { get; set; }

    public Address DeliveryAddress { get; set; }

    public Customer()
    {
        ShoppingIndex = ShoppingIndexes.Level0;
        BillingAddress = new Address();
        DeliveryAddress = new Address();
    }
}

[Serializable]
public class Address
{
    public string Street { get; set; }

    public string Zip { get; set; }

    public string City { get; set; }

    public string Country { get; set; }

    public int AreaCode { get; set; }
}

[Serializable]
public enum ShoppingIndexes
{
    Level0 = 0,
    Level1 = 10,
    Level2 = 20,
    Level3 = 30
}

Timer application

static void Main(string[] args)
    {
        var numberOfCustomers = 100000;
        var numberOfItterations = 5;

        //Console.WriteLine("Json.Net");
        //TimeSerializationAction(
        //  SerializeUsingJsonNet, numberOfCustomers, numberOfItterations);
        //TimeDeserializationAction(
        //  Newtonsoft.Json.JsonConvert.SerializeObject, DeSerializeUsingJsonNet,
        //  numberOfCustomers, numberOfItterations);

        //Console.WriteLine("ServiceStack.Text");
        //TimeSerializationAction(
        //  SerializeUsingServiceStackText, numberOfCustomers, numberOfItterations);
        //TimeDeserializationAction(
        //  ServiceStack.Text.JsonSerializer.SerializeToString, DeserializeUsingServiceStackText, 
        //  numberOfCustomers, numberOfItterations);

        Console.ReadKey();
    }

    private static void SerializeUsingJsonNet(IEnumerable<Customer> customers)
    {
        var json = customers.Select(Newtonsoft.Json.JsonConvert.SerializeObject).ToList();
    }

    private static void DeSerializeUsingJsonNet(IEnumerable<string> json)
    {
        var customers = json.Select(
            Newtonsoft.Json.JsonConvert.DeserializeObject<Customer>).ToList();
    }

    private static void SerializeUsingServiceStackText(IEnumerable<Customer> customers)
    {
        var json = customers.Select(ServiceStack.Text.JsonSerializer.SerializeToString).ToList();
    }

    private static void DeserializeUsingServiceStackText(IEnumerable<string> json)
    {
        var customers = json.Select(
            ServiceStack.Text.JsonSerializer.DeserializeFromString<Customer>).ToList();
    }

    private static void TimeSerializationAction(
        Action<IList<Customer>> action, int numOfCustomers, int numOfItterations)
    {
        var stopWatch = new Stopwatch();

        for (var c = 0; c < numOfItterations; c++)
        {
            var customers = CustomerFactory.CreateCustomers(numOfCustomers);

            stopWatch.Start();
            action(customers);
            stopWatch.Stop();

            Console.WriteLine("TotalSeconds = {0}", stopWatch.Elapsed.TotalSeconds);

            stopWatch.Reset();
        }
    }

    private static void TimeDeserializationAction(
        Func<Customer, string> serializer, Action<IList<string>> action, int numOfCustomers, int numOfItterations)
    {
        var stopWatch = new Stopwatch();

        for (var c = 0; c < numOfItterations; c++)
        {
            var customerJsons = CustomerFactory.CreateCustomers(numOfCustomers).Select(serializer).ToList();

            stopWatch.Start();
            action(customerJsons);
            stopWatch.Stop();

            Console.WriteLine("TotalSeconds = {0}", stopWatch.Elapsed.TotalSeconds);

            stopWatch.Reset();
        }
    }
}

Results

Each step: Serialization and Deserialization; has been executed one scenario at a time for each framework. Doing serialization in one execution and deserialization in another. Each time five itterations with 100000 customers in each itteration.

Scenarios: Serialization and Deserialization for:

  • Running debug mode with debugger – (This value is not representative since this isn’t how an application will be deployed)
  • Running debug mode without debugger – (This value is not representative since this isn’t how an application will be deployed)
  • Running release mode without debugger – (These are the measurements I would use for comparison, since this is how my deployed application would run)

Measurements

Json.Net vs ServiceStack.Text - Values

Average values

Json.Net vs ServiceStack.Text - Average values

Now you can decide for your self. I will continue with ServiceStack.Text, especially since deserialization is of greater importance for my project: SisoDb.

Download the example code and Excel with the results.

//Daniel