Created
January 6, 2023 00:42
-
-
Save ssg/1b860ef086189e60120a9222c2a2ca9a to your computer and use it in GitHub Desktop.
Custom benchmark code for https://twitter.com/esesci/status/1611158796814155777
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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