sub reduce_whitespace { $_[0] =~ s/\s+/ /g }
$text = 'black cat';
reduce_whitespace($text);
print $text;
> black cat
####
use Benchmark qw(cmpthese);
use strict;
use warnings;
my $original;
$original.= chr(int(rand(128))) for 1..1000;
my $add = $original;
for (1..20) {
print "\n","Length of string: ",length($original),"\n";
cmpthese (1000000,{
ref => sub { my $new = $original; by_ref(\$new) },
alias => sub { my $new = $original; by_alias($new) },
});
$original.=$add;
}
sub by_alias {
$_[0] =~ s/\s+//;
}
sub by_ref {
${ $_[0] } =~ s/\s+//;
}
####
Length of string: 1000
Rate alias ref
alias 1098901/s -- 36%
ref 806452/s -27% --
Length of string: 2000
Rate alias ref
alias 909091/s -- 20%
ref 757576/s -17% --
Length of string: 3000
Rate alias ref
alias 751880/s -- 4%
ref 724638/s -4% --
Length of string: 4000
Rate alias ref
alias 653595/s -- -5%
ref 689655/s 6% --
Length of string: 5000
Rate alias ref
alias 571429/s -- -12%
ref 649351/s 14% --
Length of string: 6000
Rate alias ref
alias 497512/s -- -18%
ref 606061/s 22% --
Length of string: 7000
Rate alias ref
alias 450450/s -- -23%
ref 581395/s 29% --
Length of string: 8000
Rate alias ref
alias 409836/s -- -23%
ref 534759/s 30% --
Length of string: 9000
Rate alias ref
alias 369004/s -- -23%
ref 476190/s 29% --
Length of string: 10000
Rate alias ref
alias 331126/s -- -21%
ref 420168/s 27% --
Length of string: 11000
Rate alias ref
alias 299401/s -- -22%
ref 381679/s 27% --
Length of string: 12000
Rate alias ref
alias 275482/s -- -22%
ref 353357/s 28% --
Length of string: 13000
Rate alias ref
alias 254453/s -- -22%
ref 325733/s 28% --
Length of string: 14000
Rate alias ref
alias 233645/s -- -23%
ref 304878/s 30% --
Length of string: 15000
Rate alias ref
alias 210526/s -- -25%
ref 282486/s 34% --
Length of string: 16000
Rate alias ref
alias 192678/s -- -27%
ref 265252/s 38% --
Length of string: 17000
Rate alias ref
alias 181488/s -- -29%
ref 255754/s 41% --
Length of string: 18000
Rate alias ref
alias 169779/s -- -31%
ref 245098/s 44% --
Length of string: 19000
Rate alias ref
alias 158983/s -- -32%
ref 233100/s 47% --
Length of string: 20000
Rate alias ref
alias 151515/s -- -34%
ref 228833/s 51% --