Skip to content

Instantly share code, notes, and snippets.

@nihen
Created August 16, 2011 03:07
Show Gist options
  • Save nihen/1148366 to your computer and use it in GitHub Desktop.
Save nihen/1148366 to your computer and use it in GitHub Desktop.
perl string
use 5.12.0;
use Benchmark qw/cmpthese/;
say alloc_once_lval() eq alloc_each() ? 'ok' : 'ng';
say alloc_once_replace() eq alloc_each() ? 'ok' : 'ng';
sub alloc_once_lval {
my $str = ' ' x 50000;
my $pos = 0;
for ( 0..9999 ) {
substr($str, $pos, 5) = sprintf('%05d', $_);
$pos += 5;
}
return $str;
}
sub alloc_once_replace {
my $str = ' ' x 50000;
my $pos = 0;
for ( 0..9999 ) {
substr($str, $pos, 5, sprintf('%05d', $_));
$pos += 5;
}
return $str;
}
sub alloc_each {
my $str = '';
for ( 0..9999 ) {
$str .= sprintf('%05d', $_);
}
return $str;
}
cmpthese(-1, {
alloc_once_lval => \&alloc_once_lval,
alloc_once_replace => \&alloc_once_replace,
alloc_each => \&alloc_each,
});
exit(0);
---- result
Rate alloc_once_lval alloc_once_replace alloc_each
alloc_once_lval 126/s -- -43% -54%
alloc_once_replace 220/s 74% -- -21%
alloc_each 277/s 119% 26% --
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment