代码之家  ›  专栏  ›  技术社区  ›  Eugene Yarmash

为什么S/^\S+\S+$//G;比两个单独的替换慢得多?

  •  13
  • Eugene Yarmash  · 技术社区  · 16 年前

    Perl常见问题条目 How do I strip blank space from the beginning/end of a string? 声明使用

    s/^\s+|\s+$//g;
    

    比分两步进行慢:

    s/^\s+//;
    s/\s+$//;
    

    为什么这个组合语句明显慢于单独的语句(对于任何输入字符串)?

    4 回复  |  直到 16 年前
        1
  •  12
  •   Alan Moore Chris Ballance    16 年前

    ~# debugperl -Dr -e 's/^\s+//g'
    Compiling REx `^\s+'
    size 4 Got 36 bytes for offset annotations.
    first at 2
    synthetic stclass "ANYOF[\11\12\14\15 {unicode_all}]".
       1: BOL(2)
       2: PLUS(4)
       3:   SPACE(0)
       4: END(0)
    stclass "ANYOF[\11\12\14\15 {unicode_all}]" anchored(BOL) minlen 1
    

    # debugperl -Dr -e 's/^\s+|\s+$//g'
    Compiling REx `^\s+|\s+$'
    size 9 Got 76 bytes for offset annotations.
    
       1: BRANCH(5)
       2:   BOL(3)
       3:   PLUS(9)
       4:     SPACE(0)
       5: BRANCH(9)
       6:   PLUS(8)
       7:     SPACE(0)
       8:   EOL(9)
       9: END(0)
    minlen 1 
    

        2
  •  9
  •   FMc TLP    16 年前

    use strict;
    use warnings;
    use Benchmark qw(cmpthese);
    
    my $ws = "   \t\t\n";
    
    for my $sz (1, 10, 100, 1000){
        my $str = $ws . ('Z' x $sz) . $ws;
        cmpthese(-2, {
            "alt_$sz" => sub { $_ = $str; s/^\s+|\s+$//g },
            "sep_$sz" => sub { $_ = $str; s/^\s+//; s/\s+$// },
        });
    }
    
               Rate alt_1 sep_1
    alt_1  870578/s    --  -16%
    sep_1 1032017/s   19%    --
    
                Rate alt_10 sep_10
    alt_10  384391/s     --   -62%
    sep_10 1010017/s   163%     --
    
                Rate alt_100 sep_100
    alt_100  61179/s      --    -92%
    sep_100 806840/s   1219%      --
    
                 Rate alt_1000 sep_1000
    alt_1000   6612/s       --     -97%
    sep_1000 261102/s    3849%       --
    
        3
  •  3
  •   Max Shawabkeh    16 年前

    ^\s+ \s+$

        4
  •  1
  •   Anon.    16 年前