Skip to content

Instantly share code, notes, and snippets.

@jrwdexter
Last active August 29, 2015 14:04
Show Gist options
  • Save jrwdexter/fb7cc8f804c7e1efbb4d to your computer and use it in GitHub Desktop.
Save jrwdexter/fb7cc8f804c7e1efbb4d to your computer and use it in GitHub Desktop.
Regex vs. where clause
using System.Diagnostics;
using System.Text.RegularExpressions;
var iterations = 1000;
var badString = "http://this.is.my/INVALID#!@STRING";
var replaceRegex = new Regex("[^a-z0-9]", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Test query
var sw = Stopwatch.StartNew();
for(int i=0; i<iterations; i++)
{
var newString = string.Join(string.Empty, badString.Where(char.IsLetterOrDigit));
if(i == 0)
Console.WriteLine(newString);
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
// Test regex
sw = Stopwatch.StartNew();
for(int i=0; i<iterations; i++)
{
var newString = replaceRegex.Replace(badString, string.Empty);
if(i == 0)
Console.WriteLine(newString);
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
// Test string builder
sw = Stopwatch.StartNew();
for(int i=0; i<iterations; i++)
{
var sb = new StringBuilder();
foreach(char c in badString)
{
if(char.IsLetterOrDigit(c))
{
sb.Append(c);
}
}
var newString = sb.ToString();
if(i == 0)
Console.WriteLine(newString);
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment