开发者

How is "my" faster than "local" in Perl?

开发者 https://www.devze.com 2023-01-13 14:07 出处:网络
Quoting from PerlMonks: The difference between my and local, But in real life, they work virtually the same? Yes. Sort of. So when should you use them?

Quoting from PerlMonks: The difference between my and local,

But in real life, they work virtually the same? Yes. Sort of. So when should you use them?

Use my when you can (it's faster than local) ...

I k开发者_如何学Gonow the lexical vs dynamic scoping difference between my and local, as discussed in this SO thread, but I am not sure why my is "faster".

What exactly do we mean when we say that a my variable is faster than a local variable in Perl?


Using local on a variable means that its previous state needs to be pushed onto a stack somewhere and restored again when the local scope is exited. Using my on a variable simply creates an entirely new variable that shadows the previous variable with the same name -- the previous one is entirely untouched, and does not need to be saved anywhere. It is simply lying in wait when the local scope is exited and it is visible again.

This pushing/popping to a stack takes resources; there's a lot of work under the hood to ensure that this works properly. (Consider cases such as an exception being thrown while in local scope, or a signal handler being executed. I'm sure you can think of more.)

Besides being more efficient, using my is much more logical. As a programmer introducing a local variable $foo, you don't need to worry about the semantic reason for the previous version of $foo, what data might already be in it, or indeed if there was a $foo already created. If sometime down the road the earlier declaration of $foo is removed, your local $foo code will break, but my $foo will be perfectly happy. Be a good programmer and keep your code in well-encapsulated pieces, which means using lexical scoping as much as you can. It's quite possible to write a large application and never need variables of package/global scope at all, especially when you use well-designed OO classes.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消