>>15
Yeah ... factors are never important ... silly math ...
And Perl is C. Well, C++ anyway. Whether you realize it or not, Perl arrays are analogs for C++ STL vectors. Most of the Perl builtins are C++ wrappers. Try running this if you dont believe me about references being more efficient. Its a simple benchmarking script that creates arrays, and does summations on a subset of those values - a simple operation that is done quite often in real world code.
#####################
use Benchmark qw(:all);
use constant LENGTH_OF_ARRAYS => 2000000;
use constant NUMBER_OF_ITERATIONS => 20000;
timethese( 100,
{
'With References' => \&UsesArrayReference,
'With Literals' => \&UsesArrayLiteral
}
);
cmpthese( -5,
{
'With References' => \&UsesArrayReference,
'With Literals' => \&UsesArrayLiteral
}
);
sub UsesArrayReference {
my $iterations = NUMBER_OF_ITERATIONS();
my $array = ReturnsArrayReference(LENGTH_OF_ARRAYS());
my $total = 0;
for( my $i = 0; $i < $iterations; $i++ ){
$total += $array->[$i];
}
return $total;
}
sub UsesArrayLiteral {
my $iterations = NUMBER_OF_ITERATIONS();
my @array = ReturnsArrayLiteral(LENGTH_OF_ARRAYS());
my $total = 0;
for( my $i = 0; $i < $iterations; $i++ ){
$total += $array[$i];
}
return $total;
}
sub ReturnsArrayReference {
my ($lengthOfArray) = @_;
my @array = (1..$lengthOfArray);
return \@array;
}
sub ReturnsArrayLiteral {
my ($lengthOfArray) = @_;
my @array = (1..$lengthOfArray);
return @array;
}
###################
Returning Perl Array literals, just like returning vector value types in C++, causes a copy of all the memory values into a new object. Thats why we get these kind of results.
###########
Benchmark: timing 100 iterations of With Literals, With References...
With Literals: 88 wallclock secs (87.83 usr + 0.05 sys = 87.87 CPU) @ 1.14/s (n=100)
With References: 44 wallclock secs (43.67 usr + 0.14 sys = 43.81 CPU) @ 2.28/s (n=100)
Rate With Literals With References
With Literals 1.14/s -- -50%
With References 2.30/s 101% --
###########
Hm ... what have we here ...
Of course, with huge sets of iterations, the copy becomes less significant. So you can probably come up with some permutation of this script which shows them as closer in terms of efficiency, but the references will still be faster.