Skip to content

Instantly share code, notes, and snippets.

@KyleMit
Created March 5, 2023 16:58
Show Gist options
  • Save KyleMit/1781d304634c703e7f4a81782166af56 to your computer and use it in GitHub Desktop.
Save KyleMit/1781d304634c703e7f4a81782166af56 to your computer and use it in GitHub Desktop.
Performance Benchmarks for Testing [a-Z]
using System;
using System.Linq;
using System.Text.RegularExpressions;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<TestAlphaCheck>();
public class TestAlphaCheck
{
[Params("hello world", "Привет, мир")]
public string Title { get; set; } = "";
[Benchmark]
public bool HasAlpha_IsAsciiLetterLinq() => Title.Any(Char.IsAsciiLetter);
[Benchmark]
public bool HasAlpha_IsAsciiLetterForEach()
{
foreach (var c in Title)
{
if (Char.IsAsciiLetter(c))
{
return true;
}
}
return false;
}
[Benchmark]
public bool HasAlpha_IsAsciiLetterForLoop()
{
for (int i = 0; i < Title.Length; i++)
{
if (char.IsAsciiLetter(Title[i]))
{
return true;
}
}
return false;
}
[Benchmark]
public bool HasAlpha_RegexInline() => Regex.IsMatch(Title, "[a-zA-Z]");
[Benchmark]
public bool HasAlpha_RegexCompiled() => AlphaRegex.IsMatch(Title);
public static readonly Regex AlphaRegex = new Regex("[a-zA-Z]", RegexOptions.Compiled);
[Benchmark]
public bool HasAlpha_RegexGenerated() => RegexExtensions.HasLetter().IsMatch(Title);
}
public static partial class RegexExtensions
{
[GeneratedRegex("[a-zA-Z]")]
public static partial Regex HasLetter();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment