http://qs321.pair.com?node_id=684005

clinton has asked for the wisdom of the Perl Monks concerning the following question:

As I understand it, passing an argument to a subroutine allows you to work on the alias within that sub, without copying the value, eg:

sub reduce_whitespace { $_[0] =~ s/\s+/ /g } $text = 'black cat'; reduce_whitespace($text); print $text; > black cat

so the size of the scalar shouldn't matter (unless you copy it :  my $string = $_[0])

But, this doesn't seem to be the case. Look at my benchmark below, which compares using an alias with pass-by-reference. Referencing and dereferencing has a cost, so I would expect it to be slower. However, as the string grows in length, the ref version wins over the alias version:

Benchmark code

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+//; }

Results

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% --

This is on Perl 5.8.8 on x86_64

Clint

Update Reformatted the results so that they are always presented in the same order, not in order of speed