我正在编写一些 Perl 脚本,需要进行大量字符串匹配。
例如:
my $str1 = "this is a test string";
my $str2 = "test";
要查看 $str1 是否包含 $str2 - 我发现有两种方法:
方法一:
使用索引函数:
if ( index($str1, $str2) != -1 ) { .... }
方法2:
使用正则表达式:
if( $str1 =~ /$str2/ ) { .... }
哪个更好?我们什么时候应该使用其中的每一个而不是另一个?
这是基准测试的结果:
use Benchmark qw(:all) ;
my $count = -1;
my $str1 = "this is a test string";
my $str2 = "test";
my $str3 = qr/test/;
cmpthese($count, {
'type1' => sub { if ( index($str1, $str2) != -1 ) { 1 } },
'type2' => sub { if( $str1 =~ $str3 ) { 1 } },
});
结果(当比赛发生时):
Rate type2 type1
type2 1747627/s -- -70%
type1 5770465/s 230% --
为了能够得出结论,需要进行测试not匹配:
my $str2 = "text";
my $str3 = qr/text/;
结果(当没有匹配时):
Rate type2 type1
type2 1857295/s -- -67%
type1 5560630/s 199% --
结论:
The index
函数比正则表达式匹配快得多。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)