[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[Omaha.pm] return from sub: array vs. arrayref
The ? was posed to me: Why would you ever return a single array ref from a sub? Why not just return an array?
One possible argument is efficiency/speed: arrayrefs can be faster if you have huge (or huge number of) arrays you're returning. Save Perl one forced copy/clear of an array.
j
j.pl:
---
use Benchmark qw(:all) ;
timethese(100000, {
'array' => 'loop_array()',
'arrayref' => 'loop_arrayref()'
});
sub loop_array {
my @a = return_array();
foreach (@a) { $_; }
}
sub return_array {
@ret = 1..100;
return @ret;
}
sub loop_arrayref {
my $a = return_arrayref();
foreach (@$a) { $_; }
}
sub return_arrayref {
@ret = 1..100;
return \@ret;
}
---
$ perl j.pl
Benchmark: timing 100000 iterations of array, arrayref...
array: 8 wallclock secs ( 8.28 usr + 0.00 sys = 8.28 CPU) @ 12077.29/s (n=100000)
arrayref: 3 wallclock secs ( 4.83 usr + 0.00 sys = 4.83 CPU) @ 20703.93/s (n=100000)