这是一个简单的起点,寻找长度不同的字符串中的单个字符。匹配变量复制源字符串,所以我希望惩罚与所需的复制量成比例。现实似乎是相反的。(这就是我们进行基准测试的原因,孩子们。)与较长字符串匹配的成本超过了制作副本的开销。回想起来,这是有道理的,因为拷贝只是
memcpy
而regex引擎必须逐字符扫描。
use 5.010;
use strict;
use warnings;
use Benchmark qw(cmpthese);
for my $n (map { 10 ** $_ } 0 .. 4) {
my $string = 'a' x $n . 0 . 'a' x $n;
print "N = $n:\n";
cmpthese(1000000, {
'w/ match vars' => sub { $string =~ /\d/p },
'w/o match vars' => sub { $string =~ /\d/ },
});
print "\n";
}
结果:
N = 1:
(warning: too few iterations for a reliable count)
Rate w/ match vars w/o match vars
w/ match vars 1184834/s -- -54%
w/o match vars 2557545/s 116% --
N = 10:
Rate w/ match vars w/o match vars
w/ match vars 1164144/s -- -49%
w/o match vars 2283105/s 96% --
N = 100:
Rate w/ match vars w/o match vars
w/ match vars 865052/s -- -45%
w/o match vars 1560062/s 80% --
N = 1000:
Rate w/ match vars w/o match vars
w/ match vars 224568/s -- -21%
w/o match vars 284333/s 27% --
N = 10000:
Rate w/ match vars w/o match vars
w/ match vars 26667/s -- -15%
w/o match vars 31480/s 18% --