Account Options

  1. Sign in
The old Google Groups will be going away soon, but your browser is incompatible with the new version.
Google Groups Home
« Groups Home
Message from discussion how does $#array work internally?
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
Rainer Weikusat  
View profile  
 More options Nov 8 2012, 4:33 pm
Newsgroups: comp.lang.perl.misc
From: Rainer Weikusat <rweiku...@mssgmbh.com>
Date: Thu, 08 Nov 2012 21:33:19 +0000
Local: Thurs, Nov 8 2012 4:33 pm
Subject: Re: how does $#array work internally?

Helmut Tessarek <tessa...@evermeet.cx> writes:
> On 08.11.12 13:33 , Rainer Weikusat wrote:
>> Assuming that @array would be the array in question, you can get the

> my bad, yes, 'array' is the name of the array.

>> number of elements by evaluating that in scalar context, eg
>> scalar(@array). $#array is a more complex operation because it is

> it is a well-formed array (no holes), so I thought $#array (if using meta
> data) is less expensvce than 'scalar @array' or does scalar @array also use
> meta data?

NB: The description below is only true for 'real' arrays.

Both calculations are done based on the structure member which holds
the highest used index in the array. Evaluating the array in scalar
context is actually less expensive for two reason:

        1. In Perl versions prio to 5.12, no intermediate 'magic SV' is
           created because the result of this evaluation is not an
           lvalue.

        2. Calculating the number of elements is done by adding 1 to
           the 'highest used index' value. But calcluating $#array
           requires adding the current 'first index' value ($[, =>
           perval(3pm)).

NB: On the computer where I tested this, the difference was about
0.000002s (2E-6).

-------------------
use Benchmark;

my @a = 1 .. 200;

timethese(-5,
          {
           len => sub {
               my $l;

               $l = @a;
               return $l;
           },

           last => sub {
               my $l;

               $l = $#a;
               return $l
           }});


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.