Skip to content

Instantly share code, notes, and snippets.

@prakashk
Created August 7, 2013 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prakashk/6178312 to your computer and use it in GitHub Desktop.
Save prakashk/6178312 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use feature qw{ say state };
use strict;
use warnings;
use Benchmark qw{:all};
use Carp;
my $str = "state declares a lexically scoped variable, just like my. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered.";
my $len = length($str);
sub str { $str }
sub outside {
die "outside" unless length( str() ) == $len;
}
sub use_my {
my $str = str();
die "use_my" unless length( $str ) == $len;
}
sub use_state {
state $str = str();
die "use_state" unless length( $str ) == $len;
}
timethese(
10_000_000,
{
'outside' => sub { outside() },
'use my' => sub { use_my() },
'use state' => sub { use_state() },
}
);
@prakashk
Copy link
Author

prakashk commented Aug 7, 2013

Benchmark: timing 10000000 iterations of outside, use my, use state...
   outside:  8 wallclock secs ( 7.09 usr +  0.00 sys =  7.09 CPU) @ 1410437.24/s (n=10000000)
    use my:  8 wallclock secs ( 8.50 usr +  0.00 sys =  8.50 CPU) @ 1176470.59/s (n=10000000)
 use state:  4 wallclock secs ( 3.03 usr +  0.00 sys =  3.03 CPU) @ 3300330.03/s (n=10000000)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment