C# • Implement the Swap/Copy Idiom

Listing 1. This test shows four different techniques to implement the copy / swap idiom. You can minimize the performance costs while still creating code that is robust in the face of exceptions. By shifting your thinking, you can create better performing code that is robust. At the same time, it's important that you measure the performance and remove the bottlenecks.

{
	List<int> l1 = GenerateList();

	System.DateTime start = DateTime.Now;
	// run the tests 1000 times:
	int testRuns = 1000;

	// First test:
	for (int i = 0; i < testRuns; i++)

	{
		for (int counter = 0; counter < l1.Count; 
			counter++)
			l1[counter] *= 2;
	}

	TimeSpan firstTest = DateTime.Now - start;

	start = DateTime.Now;

	// Second test: 
	for (int i = 0; i < testRuns; i++)

	{
		// copy / transform:
		List<int> l2 = new List<int>();
			foreach (int val in l1)
			l2.Add(2 * val);
		// swap:
		l1 = l2;
	}

	TimeSpan test2 = DateTime.Now - start;

	// Third test:
	start = DateTime.Now;
	for (int i = 0; i < testRuns; i++)

	{
		// copy / transform:
		List<int> l2 = new List<int>(l1.Count);
		foreach (int val in l1)
			l2.Add(2 * val);
		// swap:
		l1 = l2;
	}

	TimeSpan test3 = DateTime.Now - start;

	// Fourth test:
	start = DateTime.Now;
	for (int i = 0; i < testRuns; i++)

	{
		// copy / transform:
		List<int> l2 = new List<int>(l1);
		for (int counter = 0; counter < l2.Count; 
			counter++)
			l2[counter] *= 2;
		// swap:
		l1 = l2;
	}

	TimeSpan test4 = DateTime.Now - start;

	Console.WriteLine("{0}\tModify in place", firstTest);
	Console.WriteLine("{0}\tNew / add", test2);
	Console.WriteLine("{0}\tinitial capacity", test3);
	Console.WriteLine("{0}\tcopy / modify", test4);
}

static List<int> GenerateList()
{
	List<int> rval = new List<int>();
	Random gen = new Random();

	for (int i = 0; i < 100000; i++)
		rval.Add(gen.Next(0, 1000));
	return rval;
}