d的效率低于[0-9]
[0123456789][0-9]\d
\d
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);
}HUWWW