2015-10-20 114 views
2

我試圖測試正則表達式的捕獲組和非捕獲組的性能。順便說一下,捕獲組和非捕獲組之間的差別很小。 這個結果是否正常?捕獲組VS未捕獲組

[[email protected] ~]# ll -h sample.log 
-rw-r--r-- 1 root root 21M Oct 20 23:01 sample.log 

[[email protected] ~]# time grep -ciP '(get|post).*' sample.log 
20000 

real 0m0.083s 
user 0m0.070s 
sys  0m0.010s 

[[email protected] ~]# time grep -ciP '(?:get|post).*' sample.log 
20000 

real 0m0.083s 
user 0m0.077s 
sys  0m0.004s 
+0

非捕獲組需要一點點的時間比捕獲組,因爲沒有文本被保存在緩存。 –

+0

如果您希望節省時間,請去除'。*',因爲它總是匹配的,而且您沒有捕獲它。 –

回答

1

通常情況下,非捕獲組表現比捕獲組更好,因爲它們需要較少的內存分配,不進行小組賽的副本。但是,有三個重要注意事項:

  • 對於簡短短表達式而言,短匹配的區別通常非常小。
  • 開始像grep這樣的程序本身需要大量的時間和內存,並且可能會壓倒使用非捕獲組獲得的任何小改進。
  • 一些語言以相同的方式實現捕獲和非捕獲組,導致後者不會提高性能。
1

如果使用大量的捕獲組。 區別似乎更多。

謝謝大家。:)

[[email protected] ~]# time grep -ciP "(get|post)\s[^\s]+" sample.log 
20000 

real 0m0.057s 
user 0m0.051s 
sys  0m0.005s 
[[email protected] ~]# time grep -ciP "(?:get|post)\s[^\s]+" sample.log 
20000 

real 0m0.061s 
user 0m0.053s 
sys  0m0.006s 
[[email protected] ~]# time grep -ciP "(get|post)\s[^\s]+(get|post)" sample.log 
1880 

real 0m0.839s 
user 0m0.833s 
sys  0m0.005s 
[[email protected] ~]# time grep -ciP "(?:get|post)\s[^\s]+(?:get|post)" sample.log 
1880 

real 0m0.744s 
user 0m0.741s 
sys  0m0.003s