http://www.perlmonks.org?node_id=659365


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.