I'm curious if Perl internals creates a copy of the ref values to create the array? For example, the following outputs the last and first value of a delimited string:
say @{[ split( q{\|}, q{bar|is|foo} ) ]}[-1,0]; # STDOUT: foobar\n
split
and create an array ref, then copy the values of the array ref into a new array when dereferencing? Because dereferencing is so common I'm sure it's optimized, I'm just curious how expensive it is versus creating an array from the list initially, like:
my @parts = split q{\|}, q{bar|is|foo};
say @parts[-1,0];
Purpose: getting an idea of the underlying operations w/o getting too deep into the code
Perl array references Notice that the backslash operator ( \ ) is also used in front of array variable like the scalar variable. Third, in the for loop, we dereferenced the reference $ar by using @$ar . You can use curly braces @{$ar} if you want. However, shorter is better.
EDIT: from perldoc perlvar : $# is also used as sigil, which, when prepended on the name of an array, gives the index of the last element in that array.
Here is a Benchmark
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Benchmark qw(:all);
my @list = ('foo')x1_000_000;
my $str = join('|',@list);
my $count = -2;
cmpthese($count, {
'deref' => sub {
my $parts = [ split( q{\|}, $str ) ];
my @res = @$parts[-1,0];
},
'array' => sub {
my @parts = split q{\|}, $str;
my @res = @parts[-1,0];
},
});
I just change say
to an assignement.
Windows 7, perl 5.14.2
Rate deref array
deref 2.02/s -- -38%
array 3.23/s 60% --
Depending of environment, I get
Linux 64 bit, perl 5.14.2
Rate deref array
deref 3.00/s -- -35%
array 4.65/s 55% --
and Linux 32 bit, perl 5.8.4
Rate array deref
array 1.96/s -- -35%
deref 3.00/s 53% --
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With