我创建了一个演示应用程序来测试一些正则表达式的性能。我的第三个测试使用选项RightToLeft。
似乎它加快了这个过程!为什么?它有什么作用?
这是我的测试应用程序:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private const string IsRequestForDirectoryWithoutTrailingSlashRegex = @"^(?#Path:)(.*/)?(?#LastPart:)(?<!\.asmx|\.aspx/)([^./?#]+?)(?#QueryString:)(\?.*?)(?#Anchor:)?(#.*)?$";
private static string[] Tests = new string[] {
"http://localhost/manager/page.aspx",
"http://localhost/manager/",
"http://localhost/manager",
"http://localhost/manager/?param=value",
"http://localhost/manager/dir?param=value"
};
static void Main(string[] args)
{
Test1();
Test2();
Test3();
Test4();
Console.WriteLine();
Console.ReadLine();
}
public static void Test1()
{
Regex regex = new Regex(IsRequestForDirectoryWithoutTrailingSlashRegex);
DoWork("1", regex);
}
public static void Test2()
{
Regex regex = new Regex(IsRequestForDirectoryWithoutTrailingSlashRegex, RegexOptions.Compiled);
DoWork("2", regex);
}
public static void Test3()
{
Regex regex = new Regex(IsRequestForDirectoryWithoutTrailingSlashRegex, RegexOptions.Compiled | RegexOptions.RightToLeft);
DoWork("3", regex);
}
public static void Test4()
{
Regex regex = new Regex(IsRequestForDirectoryWithoutTrailingSlashRegex, RegexOptions.Compiled | RegexOptions.RightToLeft | RegexOptions.IgnoreCase);
DoWork("4", regex);
}
static void DoWork(string name, Regex regex)
{
Stopwatch sp = new Stopwatch();
sp.Start();
for (int i = 0; i < 100000; i++)
{
foreach (string s in Tests)
{
regex.IsMatch(s);
}
}
foreach (string s in Tests)
{
Console.WriteLine(":" + s + ":" + regex.IsMatch(s).ToString());
}
sp.Stop();
Console.WriteLine("Test " + name + ": " + sp.ElapsedTicks);
}
}
}