加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl:字符串索引函数或正则表达式 – 哪个更好,什么时候?

发布时间:2020-12-15 21:52:33 所属栏目:大数据 来源:网络整理
导读:我正在写一些Perl脚本,我需要做很多字符串匹配. 例如: my $str1 = "this is a test string";my $str2 = "test"; 要查看$str1是否包含$str2 – 我发现有两种方法: 方法1: 使用索引功能: if ( index($str1,$str2) != -1 ) { .... } 方法2: 使用正则表达式
我正在写一些Perl脚本,我需要做很多字符串匹配.
例如:
my $str1 = "this is a test string";
my $str2 = "test";

要查看$str1是否包含$str2 – 我发现有两种方法:

方法1:
使用索引功能:

if ( index($str1,$str2) != -1 ) { .... }

方法2:
使用正则表达式:

if( $str1 =~ /$str2/ ) { .... }

哪个更好?什么时候我们应该使用其中的每一个?

解决方法

以下是Benchmark的结果:
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%    --

为了得出结论,测试不匹配:

my $str2 = "text";
my $str3 = qr/text/;

结果(没有匹配时):

Rate type2 type1
type2 1857295/s    --  -67%
type1 5560630/s  199%    --

结论:

索引函数比正则表达式匹配快得多.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读