<?xml version="1.0" encoding="windows-1252"?>
<node id="841638" title="Re: Curious Perl Behavior..." created="2010-05-25 17:41:22" updated="2010-05-25 17:41:22">
<type id="11">
note</type>
<author id="590906">
linuxer</author>
<data>
<field name="doctext">
&lt;p&gt;You are measuring the time for creating the array reference.

Don't do:
&lt;c&gt;print sum([1..100_000]);&lt;/c&gt;

Do something like this:
&lt;code&gt;
#! /usr/bin/perl
# vim:ts=4 sw=4 sts=4 et nu fdc=3:
use strict;
use warnings;
use Benchmark qw( cmpthese );



#&gt; sub routines
#&gt; ----------------------------------------------------------------------------

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;
}

#&gt; main script
#&gt; ----------------------------------------------------------------------------

my @numbers = 1 .. 1_000_000;
cmpthese( -1, {
    'sum_list'   =&gt; sub { sum_list(@numbers);    },    
    'sum_by_ref' =&gt; sub { sum_by_ref(\@numbers); },    
});


__END__

&lt;/code&gt;

Result:
&lt;code&gt;
             Rate   sum_list sum_by_ref
sum_list   4.42/s         --       -45%
sum_by_ref 8.00/s        81%         --

&lt;/code&gt;

&lt;p&gt;I hope my point got clear ;o)

&lt;p&gt;Addendum: Tested with creating list and reference directly within function call:

&lt;code&gt;
cmpthese( -1, {
    'sum_list'   =&gt; sub { sum_list(1..1_000_000);     },    
    'sum_by_ref' =&gt; 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%         --
&lt;/code&gt;

edit: fixed missing "&lt;c&gt;1..&lt;/c&gt;" in last snippet. Thanks [ikegami]. And fixed result output as well.</field>
<field name="root_node">
841631</field>
<field name="parent_node">
841631</field>
</data>
</node>
