-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubjects.cs
More file actions
164 lines (130 loc) · 7.8 KB
/
Copy pathSubjects.cs
File metadata and controls
164 lines (130 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using RegexProof.Enums;
namespace RegexProof;
/// <summary>
/// Все измеряемые методы: проверка строки через new Regex, RegexOptions.Compiled,
/// [GeneratedRegex], статический Regex.IsMatch и RegexOptions.NonBacktracking,
/// плюс string.Contains как нижняя граница. Отдельно - методы, которые собирают
/// сам объект, и остальные способы получить результат, кроме IsMatch.
/// Каждый в своём методе с NoInlining, иначе его не найти в дизассемблированном
/// коде.
///
/// Исходник, который пишет генератор, лежит в папке Generated: его сохранение
/// включено в RegexProof.csproj свойством EmitCompilerGeneratedFiles.
///
/// Документация генератора:
/// https://learn.microsoft.com/dotnet/standard/base-types/regular-expression-source-generators
/// Разбор реализаций регулярных выражений в .NET, Stephen Toub:
/// https://devblogs.microsoft.com/dotnet/regular-expression-improvements-in-dotnet-7/
/// </summary>
public static partial class Subjects
{
// Точная подстрока. Регулярное выражение здесь не нужно, и рядом
// замеряется string.Contains, чтобы это было видно.
public const string LiteralPattern = "orders/export";
// Разбор адреса электронной почты: наборы символов, повторы, экранирование.
public const string EmailPattern = @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}";
// Повторы и варианты. На строке, где символы из его набора стоят на каждом
// шагу, разбор перебирает много вариантов - это самый тяжёлый из трёх
// паттернов.
public const string HeavyPattern = @"(?:[a-z]+\d+){2,}(?:foo|bar|baz)+end";
// Известный пример, которым принято показывать опасность регулярных
// выражений. Вложенный повтор одного и того же символа: в теории число
// вариантов разбора удваивается с каждым лишним символом.
// Проверяется в RegexBacktrackBench.
public const string NestedPattern = "^(?:a+)+$";
[GeneratedRegex(LiteralPattern)]
public static partial Regex LiteralGenerated();
[GeneratedRegex(EmailPattern)]
public static partial Regex EmailGenerated();
[GeneratedRegex(HeavyPattern)]
public static partial Regex HeavyGenerated();
[GeneratedRegex(NestedPattern)]
public static partial Regex NestedGenerated();
/// <summary>
/// Возвращает готовый экземпляр от генератора. Отдельный метод нужен,
/// чтобы замерялось обращение к генератору, а не выбор ветки в бенчмарке.
/// </summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static Regex GetGenerated(PatternKind kind) => kind switch
{
PatternKind.Literal => LiteralGenerated(),
PatternKind.Email => EmailGenerated(),
_ => HeavyGenerated(),
};
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool MatchInterpreted(Regex regex, string input) => regex.IsMatch(input);
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool MatchCompiled(Regex regex, string input) => regex.IsMatch(input);
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool MatchGenerated(Regex regex, string input) => regex.IsMatch(input);
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool MatchNonBacktracking(Regex regex, string input) => regex.IsMatch(input);
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool MatchStatic(string pattern, string input) => Regex.IsMatch(input, pattern);
// Та же статическая перегрузка, но с RegexOptions.Compiled. Пока паттерн
// лежит в кэше, объект строится один раз; после вытеснения - на каждый вызов.
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool MatchStaticCompiled(string pattern, string input) => Regex.IsMatch(input, pattern, RegexOptions.Compiled);
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool MatchContains(string needle, string input) => input.Contains(needle, StringComparison.Ordinal);
// Дальше - остальные способы получить результат, кроме IsMatch.
// IsMatch и Match останавливаются на первом совпадении, остальные проходят
// строку до конца.
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool MatchFirst(Regex regex, string input) => regex.Match(input).Success;
[MethodImpl(MethodImplOptions.NoInlining)]
public static int MatchCount(Regex regex, string input) => regex.Count(input);
[MethodImpl(MethodImplOptions.NoInlining)]
public static int MatchCollection(Regex regex, string input)
{
int total = 0;
foreach (Match match in regex.Matches(input))
{
total += match.Length;
}
return total;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static int MatchEnumerate(Regex regex, string input)
{
int total = 0;
foreach (ValueMatch match in regex.EnumerateMatches(input))
{
total += match.Length;
}
return total;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string MatchReplace(Regex regex, string input) => regex.Replace(input, "*");
// Два контроля к предыдущим методам: перегрузка Count со span вместо строки
// и обход без обращения к длине совпадения. Показывают, на что приходится
// разница между Count и EnumerateMatches.
[MethodImpl(MethodImplOptions.NoInlining)]
public static int MatchCountSpan(Regex regex, string input) => regex.Count(input.AsSpan());
[MethodImpl(MethodImplOptions.NoInlining)]
public static int MatchEnumerateCount(Regex regex, string input)
{
int total = 0;
foreach (ValueMatch _ in regex.EnumerateMatches(input))
{
total++;
}
return total;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static Regex CreateInterpreted(string pattern) => new(pattern);
[MethodImpl(MethodImplOptions.NoInlining)]
public static Regex CreateCompiled(string pattern) => new(pattern, RegexOptions.Compiled);
[MethodImpl(MethodImplOptions.NoInlining)]
public static Regex CreateNonBacktracking(string pattern) => new(pattern, RegexOptions.NonBacktracking);
// Создание вместе с первой проверкой. Отделяет работу конструктора от той,
// что приходится на первое обращение.
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool CreateCompiledAndMatch(string pattern, string input) =>
new Regex(pattern, RegexOptions.Compiled).IsMatch(input);
[MethodImpl(MethodImplOptions.NoInlining)]
public static bool CreateInterpretedAndMatch(string pattern, string input) =>
new Regex(pattern).IsMatch(input);
}