<分区>
我的英语水平很差,因为我的母语不是英语。 希望您能理解。
我在 .Net 中使用了 Regex 函数。 有一天,我尝试了用 117000 个字符串和 46 个模式调用 Regex 的 Matches 函数的测试。 结果,生成 51870 个 token 的速度比 2 毫秒快。
令人惊奇的是它只用了 2 毫秒。 将生成的集合转换为 List 花费了 250ms。 (代码如下。)
var list = collection.Cast<Match>().Select(match => match.Value).ToList();
我不敢相信,所以我试了几次,结果都一样。
我很好奇为什么Regex的Matches函数这么快。 它内部使用异步或并行机制吗?
在测试中,我调用了如下函数。
var collection = Regex.Matches(targetString(117000), this.rule(46), RegexOptions.Multiline | RegexOptions.ExplicitCapture);
感谢阅读。
完整的源代码如下。 请在 test.txt 中输入多个字符串。 我删除了“\r”、“\n”、“\t”模式以使其简单。 结果,生成的 token 数量为 45450。 感谢您的关注。
class Program
{
static void Main(string[] args)
{
string targetString = File.ReadAllText("test.txt");
string pattern = "(\\breturn\\b)|(\\bwhile\\b)|(\\bconst\\b)|(\\belse\\b)|(\\bvoid\\b)|(\\bint\\b)|(\\bif\\b)|" +
"([_a-zA-Z][_a-zA-Z0-9]*)|([0-9]+)|" +
"(//.*$)|(\\!\\=)|(\\%\\=)|(\\>\\=)|(\\/\\=)|(\\+\\=)|(\\|\\|)|(\\-\\-)|(\\+\\+)|(\\*\\=)|(\\-\\=)|(\\<\\=)|(\\=\\=)|(\\&\\&)|(\\*\\/)|(\\/\\*)|(\\*)|(\\!)|(\\+)|(\\%)|(\\))|(\\;)|(\\()|(\\/)|" +
"(\\{)| (\\})| (\\-)| (\\])| (\\[)|(\\,)|(\\>)|(\\ )|(\\=)|(\\<)";
Stopwatch sw = new Stopwatch();
sw.Start();
var collection = Regex.Matches(targetString, pattern, RegexOptions.Multiline | RegexOptions.ExplicitCapture);
sw.Stop();
Console.WriteLine("Elapsed={0}", sw.Elapsed);
sw = new Stopwatch();
sw.Start();
var list = collection.Cast<Match>().Select(match => match.Value).ToList();
sw.Stop();
Console.WriteLine("Elapsed={0}", sw.Elapsed);
}
}
我的结果如下所示。