C#
パターン6: RegexOptions.Compiledでパフォーマンス改善
出典: C# 正規表現の業務系基本 — メール / 電話 / 郵便番号 / 全角半角の入力検証5パターン — パターン6: RegexOptions.Compiledでパフォーマンス改善
using System.Diagnostics;
using System.Text.RegularExpressions;
public static class RegexPerformanceComparison
{
private const string Pattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";
// ❌都度コンパイル(遅い)
public static int CountValidNaive(string[] emails)
{
int count = 0;
foreach (var email in emails)
{
if (Regex.IsMatch(email, Pattern))
count++;
}
return count;
}
// ✅ Compiledで1回だけコンパイル(速い)
private static readonly Regex CompiledRegex = new Regex(
Pattern, RegexOptions.Compiled);
public static int CountValidCompiled(string[] emails)
{
int count = 0;
foreach (var email in emails)
{
if (CompiledRegex.IsMatch(email))
count++;
}
return count;
}
}
//使い方
class Program
{
static void Main()
{
var emails = Enumerable.Range(0, 100000)
.Select(i => $"user{i}@example.com")
.ToArray();
var sw = Stopwatch.StartNew();
int c1 = RegexPerformanceComparison.CountValidNaive(emails);
sw.Stop();
Console.WriteLine($"Naive: {sw.ElapsedMilliseconds}ms (count={c1})");
sw.Restart();
int c2 = RegexPerformanceComparison.CountValidCompiled(emails);
sw.Stop();
Console.WriteLine($"Compiled: {sw.ElapsedMilliseconds}ms (count={c2})");
}
}
▸ 実行ボタンで結果を表示
Source収録記事
この snippet は記事の「パターン6: RegexOptions.Compiledでパフォーマンス改善」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
5 件using System.Text.RegularExpressions; public static class EmailValidator {
▶ 実行可
パターン1:メールアドレス検証—簡易版が現実解
#8e620c411684
using System.Text.RegularExpressions; public static class PhoneValidator {
▶ 実行可
パターン2:電話番号検証—国内+国際対応
#f2eebc57a171
using System.Text.RegularExpressions; public static class PostalCodeValidator {
▶ 実行可
パターン3:郵便番号検証— 7桁ハイフン形式
#da3fce3a8fab
using System.Text.RegularExpressions; public static class CharTypeValidator {
▶ 実行可
パターン4:全角半角判定— Unicode範囲
#50a671243a77
using System; using System.Text.RegularExpressions; public static class FormatValidator
▶ 実行可
パターン5:数値・日付フォーマット検証
#5f14a216eab8
