How is “my” faster than “local” in Perl?

前端 未结 2 767
借酒劲吻你
借酒劲吻你 2020-12-16 17:02

Quoting from PerlMonks: The difference between my and local,

But in real life, they work virtually the same? Yes. Sort of. So when shoul

2条回答
  •  粉色の甜心
    2020-12-16 17:16

    local is probably slower because of the need to save the old value, but the speed of local vs my should not come into the discussion at all. The speed savings is minuscule:

               Rate local    my
    local 7557305/s    --   -2%
    my    7699334/s    2%    --
    

    and the features of the two are radically different. The results above come from the following benchmark:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Benchmark;
    
    our $x;
    
    my %subs = (
        local => sub {
            local $x = 42;
            return $x;
        },
        my => sub {
            my $x = 42;
            return $x;
        }
    );
    
    for my $sub (keys %subs) {
        print "$sub: ", $subs{$sub}(), "\n";
    }
    
    Benchmark::cmpthese -1, \%subs;
    

提交回复
热议问题