return \@array or @array

Gareth Harper spansh+london at gmail.com
Thu Sep 12 15:33:25 BST 2013


The below script pretty reliably puts func1 slower than func2, albeit by
only about a second on a pretty beefy machine.

use strict;
use Time::HiRes qw( time );

sub func1 {
    my @array = (1..40000000);
    return @array;
}

sub func2 {
    my @array = (1..40000000);
    return \@array;
}

my $a = 0;
my $first = time;
foreach my $foo (@{func2()}) {
    $a++;
}
my $second = time;

$a = 0;
my $third = time;
foreach my $foo (func1) {
    $a++;
}
my $fourth = time;


print $second - $first . "\n";
print $fourth - $third . "\n";



On 12 September 2013 15:08, Joel Bernstein <joel at fysh.org> wrote:

> You're wrong. Where you're going wrong is assuming that "return @foo" is
> going to "return an array". It returns a list of values, the same list that
> the array held in the subroutine scope.
>
> That is:
>
> sub foo {
>   my @foo = 1..100;
>   return @foo;
> }
>
> sub bar {
>   my @bar = 1..100;
>   return \@bar;
> }
>
> foo() will return a list of 99 elements.
> bar() will return a list of 1 element, which is a reference to an array
> containing 99 elements.
>
> Does that make more sense?
>
> /joel
>
>
> On 12 September 2013 16:02, Jérôme Étévé <jerome.eteve at gmail.com> wrote:
>
> > Hi all,
> >
> > I reckon there's a popular belief going around that A is "faster" than B
> >
> > sub fA{ ... ; return \@array; }
> > sub fB{ ... ; return @array; }
> >
> > foreach my $thing ( @{fa()} ){ ... }
> > foreach my $thing ( fB() ){ ... }
> >
> > My almost blind faith in the Perl internals gives me the gut feeling
> > that as arrays are a very native Type in Perl, and the underlying AV
> > holds a reference anyway (at the end of the day, it's C..), it
> > shouldn't make much difference.
> >
> > And that building a Perl reference of something that's already a C
> > space reference isn't going to help much.
> >
> > Any insight?
> >
> > Cheers,
> >
> > Jerome.
> >
> > --
> > Jerome Eteve
> > +44(0)7738864546
> > http://www.eteve.net/
> >
> >
>


More information about the london.pm mailing list