Perl v5.28.1
基准测试:
use common::sense;
use Benchmark qw(:all);
my $UPPER = 10_000_000;
my $str = 'foo bar baz';
cmpthese(10, {
'empty for-loop' => sub {
for my $i (1..$UPPER) {}
},
'regex match' => sub {
for my $i (1..$UPPER) {
$str =~ /foo/;
}
},
'regex match (single compile)' => sub {
my $re = qr/foo/;
for my $i (1..$UPPER) {
$str =~ $re;
}
},
'regex match (anchor)' => sub {
for my $i (1..$UPPER) {
$str =~ /^foo/;
}
},
'regex match (anchor) (single compile)' => sub {
my $re = qr/^foo/;
for my $i (1..$UPPER) {
$str =~ $re;
}
},
});
结果如下:
s/iter regex match (anchor) (single compile) regex match (single compile) regex match (anchor) regex match empty for-loop
regex match (anchor) (single compile) 3.83 -- -21% -60% -84% -97%
regex match (single compile) 3.04 26% -- -50% -80% -96%
regex match (anchor) 1.53 151% 99% -- -61% -92%
regex match 0.601 537% 405% 154% -- -81%
empty for-loop 0.117 3170% 2496% 1205% 414% --
因为foo恰好出现在字符串开头,所以我期望在正则表达式中添加明确的锚点(^)不会对性能造成影响,而不是让性能减半!
此外,我读到过这样的内容:即使包含在循环内部,Perl也足够智能,不会重新编译包含固定字符串的表达式。但是,为什么试图手动/显式地将表达式预编译为变量$re会导致如此大的性能损失?!
我将搜索子字符串“foo”更改为“asdf”(它不存在于$str中),并且锚定确实可以让引擎更早地退出搜索。但是将表达式分配给变量仍然会对性能造成巨大的影响 - 远远超出我的预期!
Rate regex match (single compile) regex match (anchor) (single compile) regex match regex match (anchor) empty for-loop
regex match (single compile) 0.401/s -- -10% -79% -83% -96%
regex match (anchor) (single compile) 0.447/s 11% -- -76% -81% -95%
regex match 1.88/s 369% 321% -- -19% -79%
regex match (anchor) 2.33/s 481% 421% 24% -- -75%
empty for-loop 9.17/s 2185% 1951% 387% 294% --
总结两个问题:
- 为什么字符串起始锚定符会减半性能?
- 编译表达式(qr//)到变量中为什么比在行内使用同一表达式慢80%?