Skip to content

Instantly share code, notes, and snippets.

@elithompson
Forked from stefanrusek/gist:3436540
Created August 23, 2012 21:31
Show Gist options
  • Save elithompson/3442106 to your computer and use it in GitHub Desktop.
Save elithompson/3442106 to your computer and use it in GitHub Desktop.
It turns out HashSet<string> is SUPER fast!
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace tpl_await_test
{
class StringTest
{
static Random rnd = new Random();
static string chars = "1234567890qwertyuiopasdfghjklzxcvbnm.";
static string[] good = GenerateStrings(100).ToArray();
static string[] all = good.Concat(GenerateStrings(100)).OrderBy(s => rnd.Next()).ToArray();
private static IEnumerable<string> GenerateStrings(int c)
{
for (var i = 0; i < c; i++)
yield return GenerateString();
}
private static string GenerateString()
{
var sb = new StringBuilder();
var l = rnd.Next(15, 35);
for (var i = 0; i < l; i++)
sb.Append(chars[rnd.Next(chars.Length)]);
return sb.ToString();
}
public void Run()
{
Contains(1);
HashSet(1);
RegexSlow(1);
RegexFast(1);
var sw = new Stopwatch();
var runs = 100000;
sw.Reset();
sw.Start();
Contains(runs);
sw.Stop();
Console.WriteLine("Contains {0}", sw.Elapsed);
sw.Reset();
sw.Start();
HashSet(runs);
sw.Stop();
Console.WriteLine("HashSet {0}", sw.Elapsed);
sw.Reset();
sw.Start();
RegexSlow(runs);
sw.Stop();
Console.WriteLine("RegexSlow {0}", sw.Elapsed);
sw.Reset();
sw.Start();
RegexFast(runs);
sw.Stop();
Console.WriteLine("RegexFast {0}", sw.Elapsed);
}
private void Contains(int p)
{
for (var i = 0; i < p; i++)
good.Contains(all[i % all.Length]);
}
HashSet<string> set;
private void HashSet(int p)
{
if (set == null)
set = new HashSet<string>(good, StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < p; i++)
set.Contains(all[i % all.Length]);
}
Regex reS;
private void RegexSlow(int p)
{
if (reS == null)
reS = new Regex(string.Join("|", good.Select(s => Regex.Escape(s)).ToArray()), RegexOptions.IgnoreCase);
for (var i = 0; i < p; i++)
reS.IsMatch(all[i % all.Length]);
}
Regex reF;
private void RegexFast(int p)
{
if (reF == null)
reF = new Regex(string.Join("|", good.Select(s => Regex.Escape(s)).ToArray()), RegexOptions.IgnoreCase | RegexOptions.Compiled);
for (var i = 0; i < p; i++)
reF.IsMatch(all[i % all.Length]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment