http://www.perlmonks.org?node_id=841638


in reply to Curious Perl Behavior...

You are measuring the time for creating the array reference. Don't do: print sum([1..100_000]); Do something like this:

#! /usr/bin/perl # vim:ts=4 sw=4 sts=4 et nu fdc=3: use strict; use warnings; use Benchmark qw( cmpthese ); #> sub routines #> ------------------------------------------------------------------- +--------- sub sum_list { my @numbers = @_; my $sum = 0; for my $num ( @numbers ) { $sum += $num; } return $sum; } sub sum_by_ref { my ( $numbers_ref ) = @_; my $sum = 0; for my $num ( @$numbers_ref ) { $sum += $num; } return $sum; } #> main script #> ------------------------------------------------------------------- +--------- my @numbers = 1 .. 1_000_000; cmpthese( -1, { 'sum_list' => sub { sum_list(@numbers); }, 'sum_by_ref' => sub { sum_by_ref(\@numbers); }, }); __END__
Result:
Rate sum_list sum_by_ref sum_list 4.42/s -- -45% sum_by_ref 8.00/s 81% --

I hope my point got clear ;o)

Addendum: Tested with creating list and reference directly within function call:

cmpthese( -1, { 'sum_list' => sub { sum_list(1..1_000_000); }, 'sum_by_ref' => sub { sum_by_ref([1..1_000_000]); }, }); Result: Rate sum_list sum_by_ref sum_list 4.13/s -- -9% sum_by_ref 4.55/s 10% --
edit: fixed missing "1.." in last snippet. Thanks ikegami. And fixed result output as well.