【发布时间】:2011-04-22 18:54:51
【问题描述】:
在讨论在 Perl 中使用 index() 搜索子字符串的相对优点时,我决定编写一个微型基准测试来证明我之前看到的在查找子字符串时索引比正则表达式更快。这是基准测试代码:
use strict;
use warnings;
use Benchmark qw(:all);
my @random_data;
for (1..100000) {
push(@random_data, int(rand(1000)));
}
my $warn_about_counts = 0;
my $count = 100;
my $search = '99';
cmpthese($count, {
'Using regex' => sub {
my $instances = 0;
my $regex = qr/$search/;
foreach my $i (@random_data) {
$instances++ if $i =~ $regex;
}
warn $instances if $warn_about_counts;
return;
},
'Uncompiled regex with scalar' => sub {
my $instances = 0;
foreach my $i (@random_data) {
$instances++ if $i =~ /$search/;
}
warn $instances if $warn_about_counts;
return;
},
'Uncompiled regex with literal' => sub {
my $instances = 0;
foreach my $i (@random_data) {
$instances++ if $i =~ /99/;
}
warn $instances if $warn_about_counts;
return;
},
'Using index' => sub {
my $instances = 0;
foreach my $i (@random_data) {
$instances++ if index($i, $search) > -1;
}
warn $instances if $warn_about_counts;
return;
},
});
令我惊讶的是它们的表现如何(在最近的 MacBook Pro 上使用 Perl 5.10.0)。按速度降序排列:
- 带有文字的未编译正则表达式 (69.0 ops/sec)
- 使用索引(61.0 ops/sec)
- 标量的未编译正则表达式 (56.8 ops/sec)
- 使用正则表达式(17.0 ops/sec)
谁能解释一下 voodoo Perl 使用什么来获得两个未编译的正则表达式的执行速度以及索引操作?这是我用来生成基准的数据中的问题(在 100,000 个随机整数中寻找 99 的出现)还是 Perl 能够进行运行时优化?
【问题讨论】:
-
所以从每个人的 cmets 来看,很明显我没有意识到我错过了
/o标志来实际编译代码。我已经添加了这个,我发布的时间并没有显着偏离,除了“未编译的带有标量的正则表达式”现在与索引相当。 -
这一切似乎都归结为使用来自标量的正则表达式,即
qr/99/导致执行速度比任何内联正则表达式都慢,这与未优化的子字符串搜索相当。跨度>
标签: regex perl benchmarking