相关疑难解决方法(0)

\ d效率低于[0-9]

我昨天做了评论,其中有人曾用一个答案[0123456789]正则表达式,而不是[0-9]\d.我说使用范围或数字说明符比使用字符集更有效.

我决定今天测试一下,并且我惊讶地发现(至少在C#正则表达式引擎中)\d似乎效率低于其他两个似乎没有太大差别的.这是我的10000个随机字符串1000个随机字符的测试输出,其中5077实际上包含一个数字:

Regular expression \d           took 00:00:00.2141226 result: 5077/10000
Regular expression [0-9]        took 00:00:00.1357972 result: 5077/10000  63.42 % of first
Regular expression [0123456789] took 00:00:00.1388997 result: 5077/10000  64.87 % of first
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是有两个原因:

  1. 我原以为该范围的实施要比套装更有效.
  2. 我无法理解为什么\d会比这更糟糕[0-9].还有\d简单的简写[0-9]吗?

这是测试代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace SO_RegexPerformance
{
    class Program
    {
        static void Main(string[] args)
        {
            var rand = new …
Run Code Online (Sandbox Code Playgroud)

c# regex performance

1214
推荐指数
4
解决办法
8万
查看次数

标签 统计

c# ×1

performance ×1

regex ×1