代码之家  ›  专栏  ›  技术社区  ›  Daniel Vandersluis

汉字课与速记课的表现

  •  4
  • Daniel Vandersluis  · 技术社区  · 14 年前

    在回答另一个问题时,有人提出,在性能方面,显式字符类之间可能存在差异( [0-9] )还有速记课( \d ). 我最初的反应是,如果真的存在差异,那就可以忽略不计了,但我没有(也找不到)任何关于它的信息,也不知道如何测试它。

    同样,这两者之间是否存在不可忽视的差异 [^0-9] [^\d] \D ?

    2 回复  |  直到 14 年前
        1
  •  3
  •   dawg    14 年前

    当有疑问时,基准!

    \d+ 速度确实更快。基督教青年会。

    use strict; use warnings;
    use Benchmark qw(:all);
    use feature "switch";
    
    my $r1='\d+';
    my $r2='[0-9]+';
    my $r3='[[:digit:]]+';
    
    sub test {
        my @lines = <DATA>;
        $_=shift;
        my $RegEx=(caller(0))[3];
        given($_) {
            when(1) { $RegEx=$r1; }
            when(2) { $RegEx=$r2; }
            when(3) { $RegEx=$r3; }
            default { die "$RegEx can't deal with $_\n"; }
        }   
        my $ln;
        my $total;
        my @numbers;
        foreach my $line (@lines) {
            $total=0;
            @numbers=$line=~/($RegEx)/g;
            $total+=$_ for (@numbers) ;
            $ln=$numbers[$#numbers];
            $total-=$ln;
            if ($ln != $total) {
                print "Bad RegEx result: Last Num != total in line!\n";
                print "Total=$total, ln=$ln, line:$line";
                die;
            }       
        }   
    }
    
    cmpthese(-10, {$r1=>'test(1)', $r2=>'test(2)', $r3=>'test(3)'});
    
    
    __DATA__
    Clip clap clock 1 mouse ran up the clock with 3 hands. The total here is 4.
    The mouse with 2 ears followed. The total here is 2.
    After that, the 6 wiskered mouse did dances with 14 second timing. 20.
    It is hard to make up 5 lines with 2 or 3 numbers in each line. 10.
    You start thinking about nurserey rhymes with 1 o 2 or 3 number. 6.
    1 12 13 123 23 13 55 66 21 45 1 373
    

                     Rate [[:digit:]]+       [0-9]+          \d+
    [[:digit:]]+ 200781/s           --          -1%          -2%
    [0-9]+       202831/s           1%           --          -1%
    \d+          204605/s           2%           1%           --
    

    在带有Perl 5.10.1的Ubuntu 10.04上:

                     Rate [[:digit:]]+       [0-9]+          \d+
    [[:digit:]]+ 264412/s           --          -3%          -6%
    [0-9]+       273202/s           3%           --          -3%
    \d+          280541/s           6%           3%           --
    
        2
  •  1
  •   James Curran    14 年前

    好吧,不知道实现(也不想在Reflector中遍历数百行代码),很难确定,所以让我们尝试一些疯狂的推测。

    • 假设A)“[J-P]”编码如下 "JKLMNOP".Contains(chr)
    • 假设B)搜索数字的速度可以通过 Char.IsDigit(chr)

    鉴于此,这归结为两个问题:

    • Regex会治疗吗 \d
    • Regex是否有可能将[0-9]识别为不同于[J-P]的特例并使用它 IsDigit 而不是 Contains

    所以,我想说有可能\d比[0-9]快。

    (注意:我使用C#/.NET作为例子,但是基本原则应该是相同的,无论平台如何)