#!/usr/bin/env perl

use strict;
use warnings;

use Benchmark 'cmpthese';

cmpthese(-30, {
    loop            => sub { loop('1') },
    assign          => sub { assign('1') },
    loop_small      => sub { loop('12') },
    assign_small    => sub { assign('12') },
    loop_large      => sub { loop('12345') },
    assign_large    => sub { assign('12345') },
});

my $BUFFER;

sub loop {
    $BUFFER .= $_[0];
    1 while parse(\$BUFFER);
}

sub assign {
    my $buffer = \($BUFFER .= $_[0]);
    1 while parse($buffer);
}

sub parse {
    my $buffer = shift;
    return substr ${$buffer}, 0, 1, '';
}

__END__

                  Rate loop_large assign_large loop_small assign_small assign loop
loop_large    572867/s         --          -0%       -42%         -47%   -62% -62%
assign_large  574321/s         0%           --       -42%         -47%   -62% -62%
loop_small    991912/s        73%          73%         --          -8%   -34% -34%
assign_small 1079848/s        88%          88%         9%           --   -28% -28%
assign       1504128/s       163%         162%        52%          39%     --  -0%
loop         1504541/s       163%         162%        52%          39%     0%   --
