Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Apr 4th, 2012  |  syntax: None  |  size: 1.12 KB  |  views: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. use common::sense;
  2. use Benchmark ':all';
  3.  
  4. package OverloadItr {
  5.     use overload
  6.         q{<>} => sub { $_[0]->next };
  7.  
  8.     sub new {
  9.         bless {
  10.             count => 10000,
  11.         }, shift;
  12.     }
  13.  
  14.     sub next {
  15.         my $count = $_[0]->{count}--;
  16.         return unless $count;
  17.         return $count;
  18.     }
  19. }
  20.  
  21. package OverloadItrWithGoto {
  22.     use overload
  23.         q{<>} => sub { goto &next };
  24.  
  25.     sub new {
  26.         bless {
  27.             count => 10000,
  28.         }, shift;
  29.     }
  30.  
  31.     sub next {
  32.         my $count = $_[0]->{count}--;
  33.         return unless $count;
  34.         return $count;
  35.     }
  36. }
  37.  
  38. say $^V;
  39. cmpthese(100, {
  40.     next => sub {
  41.         my $itr = OverloadItr->new;
  42.         while ($itr->next) {}
  43.     },
  44.     itr  => sub {
  45.         my $itr = OverloadItr->new;
  46.         while (<$itr>) {}
  47.     },
  48.     itr_goto  => sub {
  49.         my $itr = OverloadItrWithGoto->new;
  50.         while (<$itr>) {}
  51.     },
  52. });
  53.  
  54.  
  55. __END__
  56.  
  57. v5.13.7
  58.     (warning: too few iterations for a reliable count)
  59.           Rate      itr itr_goto     next
  60. itr      104/s       --      -2%     -42%
  61. itr_goto 106/s       2%       --     -40%
  62. next     179/s      71%      68%       --
clone this paste RAW Paste Data