動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

パターン6: RegexOptions.Compiledでパフォーマンス改善

出典: C# 正規表現の業務系基本 — メール / 電話 / 郵便番号 / 全角半角の入力検証5パターンパターン6: RegexOptions.Compiledでパフォーマンス改善

パターン6: RegexOptions.Compiledでパフォーマンス改善 (csharp)#228fa557c142
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})");
    }
}
▸ 実行ボタンで結果を表示
  • id: #228fa557c142
  • lines: 55
  • extracted: 2026-06-10
  • captured: 2026-06-04

Source収録記事

この snippet は記事の「パターン6: RegexOptions.Compiledでパフォーマンス改善」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

5
図鑑トップ