Skip to content

Instantly share code, notes, and snippets.

@ssg
Created January 6, 2023 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssg/1b860ef086189e60120a9222c2a2ca9a to your computer and use it in GitHub Desktop.
Save ssg/1b860ef086189e60120a9222c2a2ca9a to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Text.RegularExpressions;
namespace RegexVsToCharArray;
[MemoryDiagnoser]
public class MemoryBenchmarker
{
static readonly string[] names = { "Plague Tale", "Callisto Protocol", "God Of War", "Street Fighter 6", "Elden Ring" };
const string exceptList = "aeiur";
[Benchmark]
public IList<string> ToCharArray()
{
var query =
from name in names
where name.ToCharArray().Where(c => !exceptList.Contains(c)).Count() > 10
select name;
return query.ToList();
}
[Benchmark]
public IList<string> Regex_Inline()
{
return names
.Where(s => Regex.Replace(s, "[aeiur]+", "").Length > 10)
.ToList();
}
[Benchmark]
public IList<string> Regex_Compiled()
{
return names
.Where(s => Regex.Replace(s, "[aeiur]+", "", RegexOptions.Compiled).Length > 10)
.ToList();
}
[Benchmark]
public IList<string> CustomMatch()
{
static bool matches(string s)
{
int sum = 0;
foreach (char c in s)
{
if (!exceptList.Contains(c))
{
sum++;
}
if (sum > 10)
{
return true;
}
}
return false;
}
return names.Where(s => matches(s)).ToList();
}
[Benchmark]
public IList<string> TakeWhile()
{
return names
.Where(s => s.TakeWhile(c => !exceptList.Contains(c)).Count() > 10)
.ToList();
}
static void Main()
{
_ = BenchmarkRunner.Run<MemoryBenchmarker>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment