Hi all,
In a recent node there was some discussion about the different ways to get the count of the number of elements in an array. In that thread I expressed my personal preference for scalar(@array) over $#array + 1 or $size = @array. I didn't have any performance timings, so I figured I should see if there really is a difference. This is my timing code:

use strict; use Benchmark; my @array = (1..10000000); timethese(100000000, { 'scalar' => \&size_scalar, 'index' => \&size_index, 'context' => \&size_context } ); sub size_context { my $val1 = @array; } sub size_index { my $val2 = $#array + 1; } sub size_scalar { my $val3 = scalar(@array); }

The results (formatted to look a bit nicer):
context: 30.52 usr + 0.00 sys = 30.52 CPU @ 3277076.85/s<br> index: 42.11 usr + 0.00 sys = 42.11 CPU @ 2374732.84/s<br> scalar: 53.44 usr + 0.00 sys = 53.44 CPU @ 1871327.52/s

So, two questions here. First, is my test doing a reasonable job of timing? I don't do benchmarks like this often, so I'm worried I've hashed it up. Second, is there any obvious reason why the difference? Is scalar(@array) is slower because it requires a function call?

-Tats

In reply to Timing of Array-Size Determination Methods by Itatsumaki

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.