using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace ca
{
public class Test
{
public static void Main()
{
Regex trimmer = new Regex(@"\s\s+", RegexOptions.Compiled);
Random rng = new Random();
Stopwatch sw = new Stopwatch();
const int n = 5;
// random 1mb+ string (it's slow enough...)
StringBuilder ssb = new StringBuilder(1 * 1024 * 1024);
for (int i = 0; i < 1 * 1024 * 1024; ++i)
if (rng.Next(5) == 0)
ssb.Append(new string(' ', rng.Next(20)));
else
ssb.Append((char)(rng.Next(128 - 32) + 32));
string s = ssb.ToString();
StringBuilder tmpbuilder = new StringBuilder(s.Length);
// ===================
// ========= regex =========
sw.Start();
for (int i = 0; i < n; ++i)
{
string scopy = s;
scopy = trimmer.Replace(scopy, " ");
}
sw.Stop();
Console.WriteLine("Regex: " + sw.ElapsedMilliseconds + "ms.");
// ========= stringbuilder =========
sw.Reset(); sw.Start();
for (int i = 0; i < n; ++i)
{
string scopy = s;
bool inspaces = false;
tmpbuilder.Length = 0;
for (int k = 0; k < s.Length; ++k)
{
char c = scopy[k];
if (inspaces)
{
if (c != ' ')
{
inspaces = false;
tmpbuilder.Append(c);
}
}
else if (c == ' ')
{
inspaces = true;
tmpbuilder.Append(' ');
}
else
tmpbuilder.Append(c);
}
}
sw.Stop();
Console.WriteLine("Stringbuilder: " + sw.ElapsedMilliseconds + "ms.");
}
}
}