2015-10-20 116 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