#!/usr/bin/perl
use warnings;
use strict;
$|++;
use Benchmark qw( cmpthese );
my $str;
# short example string
$str="
this
is
a string
example";
# longer string ( 1000 lines )
# my @chars = ( 'a' .. 'z', 'A' .. 'Z' );
# for ( 1..1000 ) {
# $str .= $chars[ rand @chars ] for 0 .. rand @chars;
# $str .= "\n";
# }
cmpthese( 5000, {
perl_io => sub {
open( my $fh, "<:scalar", \$str) or die "$!\n";
my @data = <$fh>;
},
split_map => sub {
my @data=map { $_.="\n" } split (/\n/, $str);
},
regex_pike => sub {
my @data = split /(?<=\n)/, $str;
},
} );
####
Rate perl_io split_map regex_pike
perl_io 14085/s -- -46% -57%
split_map 25907/s 84% -- -20%
regex_pike 32468/s 131% 25% --
####
Rate regex_pike split_map perl_io
regex_pike 79.4/s -- -40% -56%
split_map 131/s 65% -- -27%
perl_io 181/s 128% 38% --