Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: About "state" variables in Perl 5.10

by kyle (Abbot)
on Dec 28, 2007 at 18:04 UTC ( #659365=note: print w/replies, xml ) Need Help??


in reply to About "state" variables in Perl 5.10

The main difference I see is that the initialization of state variables only happens when the function is called. Consider:

use feature qw( :5.10 ); sub uncalled_sub { state $huge = huge_data_structure(); return; } print 'mem usage: ', my_mem(), "\n"; sub huge_data_structure { return [ ( 'x' x 1_000 ) x 100_000 ]; } sub my_mem { my ($proc_info) = grep { $_->[2] == $$ } map { [ split ] } `ps l | tail -n +2` +; return $proc_info->[6]; } __END__ mem usage: 11220

Compare to:

{ my $huge = huge_data_structure(); sub uncalled_sub { # state $huge = huge_data_structure(); return; } } print 'mem usage: ', my_mem(), "\n"; __END__ mem usage: 116132

Both tests were performed with Perl 5.10.0. You get the same kind of side effect (with time instead of memory) if initialization is a long_arduous_task().

Consider also:

print counter(), "\n"; { my $count = 0; sub counter { $count++ } } print counter(), "\n"; __END__ 0 0

Compare to:

use feature qw( :5.10 ); print counter(), "\n"; sub counter { state $count = 0; return $count++; } print counter(), "\n"; __END__ 0 1

Under ordinary circumstances, you won't notice either problem. Your initialization is fast, and it happens inside something you used, not in the middle of your program.

I think it also helps maintainability. You have the variable that's relevant to the function inside it instead of outside it. Even if they're right next to each other (as you have them), they could get separated later, and you don't want one of them left behind in some refactoring.

Replies are listed 'Best First'.
Re^2: About "state" variables in Perl 5.10
by citromatik (Curate) on Dec 29, 2007 at 12:58 UTC
    The main difference I see is that the initialization of state variables only happens when the function is called

    Yes, that is a good difference. Thanks!

    Consider also:
    print counter(), "\n"; { my $count = 0; sub counter { $count++ } } print counter(), "\n"; __END__ 0 0

    This one is easy to overcome, just putting the code in a BEGIN block:

    print counter(), "\n"; BEGIN{ my $count = 0; sub counter { $count++ } } print counter(), "\n"; __END__ 1 0
    citromatik

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://659365]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2021-05-15 02:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Perl 7 will be out ...





    Results (150 votes). Check out past polls.

    Notices?