using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
public class Test
{
public static void Main()
{
var random = new Random(7);
var sb = new StringBuilder();
for (int i = 0; i < 80; i++)
{
sb.Append((char)random.Next('a', 'z'));
}
var input = sb.ToString();
TimeIt(new RegexSolution(), input);
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
TimeIt(new IteratorSolution(), input);
}
private static void TimeIt(ISolution solution, string input)
{
// Warmup.
var x = solution.ToBuckets(input).Count();
var sw = Stopwatch.StartNew();
for (int i = 0; i < 100000; i++)
{
x += solution.ToBuckets(input).Count();
}
sw.Stop();
Console.WriteLine("{0}, {1}", solution.Name, x);
Console.WriteLine(sw.Elapsed);
}
private interface ISolution
{
string Name { get; }
IEnumerable<string> ToBuckets(string input);
}
private class RegexSolution : ISolution
{
public string Name
{
get { return "Regex"; }
}
public IEnumerable<string> ToBuckets(string input)
{
return Regex.Match(input, "^(?<bucket>.{4})+$")
.Groups["bucket"].Captures
.Cast<Capture>()
.Select(capture => capture.Value);
}
}
private class IteratorSolution : ISolution
{
public string Name
{
get { return "Iterator"; }
}
public IEnumerable<string> ToBuckets(string input)
{
const int Length = 4;
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length % Length != 0)
{
throw new ArgumentException(string.Format("Argument length must be a multiple of {0}", Length));
}
for (var i = 0; i < input.Length; i += Length)
{
yield return input.Substring(i, Length);
}
}
}
}