gpt4 book ai didi

perl - 为什么使用 qr 预编译的正则表达式比使用常量正则表达式慢?

转载 作者:行者123 更新时间:2023-12-05 00:52:22 24 4
gpt4 key购买 nike

我刚看到this question关于在 Perl 中优化特定的正则表达式。我想知道我的机器可以做多少匹配,所以我尝试了以下简单的基准测试:

  • 案例 1 - 使用由 qr 预编译的正则表达式
  • 案例 2 - 普通 /regex/匹配
  • use 5.014;
    use warnings;

    use Benchmark qw(:all);

    my $str = "SDZ";
    my $qr = qr/S?T?K?P?W?H?R?A?O?\*?E?U?F?R?P?B?L?G?T?S?D?Z?/;

    say "match [$&]" if( $str =~ $qr );

    my $res = timethese(-10, {
    stdrx => sub { $str =~ /S?T?K?P?W?H?R?A?O?\*?E?U?F?R?P?B?L?G?T?S?D?Z?/ },
    qr_rx => sub { $str =~ $qr },
    });

    cmpthese $res;

    令我惊讶的是,它给出了以下结果:

    match [SDZ]
    Benchmark: running qr_rx, stdrx for at least 10 CPU seconds...
    qr_rx: 10 wallclock secs ( 9.99 usr + 0.01 sys = 10.00 CPU) @ 1089794.90/s (n=10897949)
    stdrx: 11 wallclock secs (10.58 usr + 0.04 sys = 10.62 CPU) @ 1651340.11/s (n=17537232)
    Rate qr_rx stdrx
    qr_rx 1089795/s -- -34%
    stdrx 1651340/s 52% --

    即平原 $str =~ /regex/比使用 $str =~ qr 快约 50% .我期待相反的结果。

    难道我做错了什么?为什么我得到这个结果?

    编辑:

    刚刚 downloaded引用的书,我有很多东西要学:)。但是,引用的书还说:

    If a regex literal has no variable interpolation, Perl knows that the regex can’t change from use to use, so after the regex is compiled once, that compiled form is saved (“cached”) for use whenever execution again reaches the same code. The regex is examined and compiled just once, no matter how often it’s used during the program’s execution.


    所以,在上面的两个正则表达式都是没有变量插值的文字。因此,“预编译”正则表达式 应该和普通的一样快 .在示例中,它慢了 50%。

    池上解释了为什么 $str =~ $qr比较慢。 (老实说,“较慢”不是正确的术语,因为我们谈论的是几微秒...... :))

    但是 perl 文档说:

    Precompilation of the pattern into an internal representation at the moment of qr() avoids the need to recompile the pattern every time a match /$pat/ is attempted.



    从普通 perl 用户(“不是一些高级 perl 僧侣”)的角度来看,这意味着:预编译您的模式 - 它会更快,但事实是 - 只有当正则表达式包含一些“非静态“部分...

    老实说,我仍然没有完全理解这一点——但得到了一本书并打算学习。 :) 也许在文档中多一句 - 可以帮助初学者不要误解 qr当他们开始学习时。

    谢谢你们!

    最佳答案

    正则表达式模式在编译时编译,如果它们不插值。 qr// 中的正则表达式都没有运算符也不是 stdrx 中匹配运算符中的那个插值,所以两者都是在编译时编译的。

    qr_rx 中花费的额外 30μs测试用于“编译”第三个正则表达式:qr_rx 中匹配运算符中的那个.别忘了 $_ =~ $re $_ =~ m/$re/的缩写.现在,当整个模式由内插预编译正则表达式组成时,实际上不会发生编译,因为这种情况是专门处理的,但显然仍然需要一些时间来诱使匹配操作使用预编译正则表达式。 (也许它需要克隆它?)

    关于perl - 为什么使用 qr 预编译的正则表达式比使用常量正则表达式慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009931/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com