types_of_variables.pl 571 B

123456789101112131415161718192021222324252627282930313233
  1. #!/usr/bin/perl
  2. # Performance comparison between `state`, `my` and global variables.
  3. use 5.010;
  4. use Benchmark qw(cmpthese);
  5. cmpthese(
  6. -1,
  7. {
  8. my => sub {
  9. my $x = rand(1);
  10. $x + 1;
  11. },
  12. state => sub {
  13. state $x;
  14. $x = rand(1);
  15. $x + 1;
  16. },
  17. global => sub {
  18. $main::global = rand(1);
  19. $main::global + 1;
  20. }
  21. }
  22. );
  23. __END__
  24. Rate my global state
  25. my 12105605/s -- -17% -44%
  26. global 14563555/s 20% -- -32%
  27. state 21462081/s 77% 47% --