The current .NET 7.0 comes with a new source code generator that I presented in the previous part of the series. You can use it via annotation instead of instantiating the RegEx class:
Advertisement
dr Holger Schwichtenberg is Chief Technology Expert at MAXIMAGO, which offers innovation and experience-driven software development, including in highly critical safety-related areas. He is also head of the expert network www.IT-Visions.de, which supports numerous medium-sized and large companies with advice and training in the development and operation of software with 38 renowned experts.
public partial class Checker // Partial class { (GeneratedRegex(@”\w+((-+.’)\w+)*@\w+((-.)\w+)*\.\w+((-.)\w+ )*”)) // Partial method then implemented by SG: public partial Regex EMailRegEx(); }
A performance comparison (see Figure 1) shows that the new source generator is the fastest variant for the one-time execution of a regular expression. At 100 repeated uses, things look a little different. Here, the solution compiled at runtime clearly wins, provided the compilation is done only once:
Regex re2;
public string ExtractEMail_ClassicCompiledPrepared(string input)
{
if (re2 == null) re2 =
new Regex(@”\w+((-+.’)\w+)*@\w+((-.)\w+)*\.\w+((-.)\w+)*”,
RegexOptions.Compiled);
var m = re2.Match(input);
return m.Value;
}
The interpreted variant is also faster if you only instantiate the RegEx object once:
Regex re1;
public string ExtractEMail_InterpretedPrepared(string input)
{
if (re1 == null) re1 =
new Regex(@”\w+((-+.’)\w+)*@\w+((-.)\w+)*\.\w+((-.)\w+)*”);
return re1.Match(input).Value;
}
When using the source generator, it doesn’t make much difference whether you reuse the instance of the partial class or create it over and over again, because the generated code uses a static member of the regular expression, as shown in Figure 1.
Advertisement
Comparison of the performance of the regular expression source generator with the applications of the RegEx class (Fig. 1)
.NET 7.0 also improves regular expression performance when using the RegEx class. Microsoft explains the details in a blog entry.
(rme)
Go to home page
#.NET #Regular #expression #source #generator #performance