Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is it to dereference an array ref in Perl?

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
  • Does the operation first generate a list via split and create an array ref, then copy the values of the array ref into a new array when dereferencing?
  • Does it morph the current arrayref in place?

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

like image 676
vol7ron Avatar asked Sep 24 '13 14:09

vol7ron


People also ask

How do I dereference an array reference in Perl?

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.

What does $# mean in Perl?

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.


1 Answers

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%    --
like image 191
Toto Avatar answered Nov 15 '22 05:11

Toto