亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

d的效率低于[0-9]

d的效率低于[0-9]

搖曳的薔薇 2019-06-12 15:45:11
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個贊

感謝ByteBlast在文檔中注意到了這一點。只需更改regex構造函數:

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


查看完整回答
反對 回復 2019-06-12
  • 3 回答
  • 0 關注
  • 721 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號