d的效率低于[0-9]我昨天对有人用[0123456789]在.正则表达式而不是[0-9]或\d..我说使用范围或数字说明符可能比字符集更有效。今天我决定对这个问题进行测试,并意外地发现(至少在C#regex引擎中)。\d似乎比另外两个人效率低,而这两者似乎并没有太大的不同。下面是我的测试输出,超过10000个随机字符串的1000个随机字符,其中5077实际上包含一个数字:Regular expression \d took 00:00:00.2141226 result: 5077/10000Regular expression [0-9]
took 00:00:00.1357972 result: 5077/10000 63.42 % of firstRegular expression [0123456789] took 00:00:00.1388997
result: 5077/10000 64.87 % of first这对我来说是个惊喜,有两个原因:我原以为这个范围会比设定有效得多。我不明白为什么\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 Random(1234);
var strings = new List<string>();
//10K random strings
for (var i = 0; i < 10000; i++)
{
//Generate random string
var sb = new StringBuilder();
for (var c = 0; c < 1000; c++)
{
//Add a-z randomly
sb.Append((char)('a' + rand.Next(26)));
}
//In roughly 50% of them, put a digit
if (rand.Next(2) == 0)
{
//Replace one character with a digit, 0-9
sb[rand.Next(sb.Length)] = (char)('0' + rand.Next(10));
}
strings.Add(sb.ToString());
}
var baseTime = testPerfomance(strings, @"\d");
Console.WriteLine();
var testTime = testPerfomance(strings, "[0-9]");
Console.WriteLine(" {0:P2} of first", testTime.TotalMilliseconds / baseTime.TotalMilliseconds);
testTime = testPerfomance(strings, "[0123456789]");
Console.WriteLine(" {0:P2} of first", testTime.TotalMilliseconds / baseTime.TotalMilliseconds);
}
3 回答
HUWWW
TA贡献1874条经验 获得超12个赞
var rex = new Regex(regex, RegexOptions.ECMAScript);
Regex \d took 00:00:00.1355787 result: 5077/10000Regex [0-9] took 00:00:00.1360403 result: 5077/10000 100.34 % of firstRegex [0123456789] took 00:00:00.1362112 result: 5077/10000 100.47 % of first
- 3 回答
- 0 关注
- 694 浏览
添加回答
举报
0/150
提交
取消