using System.Collections.Generic;
using System.Diagnostics;
public static void Main()
var stopWatch = new Stopwatch();
var method1Runs = new TimeSpan[runCount];
var method2Runs = new TimeSpan[runCount];
Console.WriteLine(string.Format("Results running DotNetPerls' test methods {0} times.", runCount));
var listA = new List<int>(100);
for (var i = 0; i < runCount; i++)
method1Runs[i] = stopWatch.Elapsed;
var listB = new List<int>(100);
for (var i = 0; i < runCount; i++)
method2Runs[i] = stopWatch.Elapsed;
ReportMethodResults(method1Runs, "Clear");
ReportMethodResults(method2Runs, "New");
static List<int> Method1(List<int> list)
for (int i = 0; i < 100; i++)
static List<int> Method2(List<int> list)
list = new List<int>(100);
for (int i = 0; i < 100; i++)
static void ReportMethodResults(IEnumerable<TimeSpan> timeSpans, string methodName)
var longestTime = timeSpans.Max(o => o.TotalNanoseconds());
var shortestTime = timeSpans.Min(o => o.TotalNanoseconds());
var averageTime = timeSpans.Average(o => o.TotalNanoseconds());
var medianTime = timeSpans.Median(o => o.TotalNanoseconds());
Console.WriteLine(string.Format("Longest time {0}: {1}ns", methodName, longestTime));
Console.WriteLine(string.Format("Shortest time {0}: {1}ns", methodName, shortestTime));
Console.WriteLine(string.Format("Average time {0}: {1}ns", methodName, averageTime));
Console.WriteLine(string.Format("Median time {0}: {1}ns", methodName, medianTime));
static class ExtensionMethods
public static double TotalNanoseconds(this TimeSpan timeSpan)
const int nanosecondsInMillisecond = 1000000;
return timeSpan.TotalMilliseconds * nanosecondsInMillisecond;
public static double Median<TSource>(this IEnumerable<TSource> source, Func<TSource, double> selector)
var orderedItems = source.Select(selector).OrderBy(o => o).ToArray();
if (orderedItems.Length == 0)
throw new ArgumentOutOfRangeException("Cannot find the Median of an empty set.");
if (orderedItems.Length % 2 == 1)
return orderedItems[(orderedItems.Length - 1) / 2];
var itemAIndex = orderedItems.Length / 2;
var itemBIndex = itemAIndex - 1;
return (orderedItems[itemAIndex] + orderedItems[itemBIndex]) / 2;