Not the fastest? Let's see what we can do about it.

That's tail-end recursion, so it can be optimized:

sub equal { return 1 if @_ < 2; return 0 if $_[0] ne $_[1]; shift; goto(&equal); }

And the recursive call can be eliminated completely:

sub equal { while (@_ >= 2) { return 0 if $_[0] ne $_[1]; shift; } return 1; }

Benchmarks:

use strict; use warnings; use Benchmark qw( cmpthese ); my @list = ('1')x10; sub equal_pm {@_ < 2 || $_[0] eq $_[1] && equal_pm(@_[1..$#_])} sub equal_i { return 1 if @_ < 2; return 0 if $_[0] ne $_[1]; shift; goto(&equal_i); } sub equal_i2 { while (@_ >= 2) { return 0 if $_[0] ne $_[1]; shift; } return 1; } cmpthese(-3, { equal_pm => sub { my $rv = equal_pm(@list) ?1:0; 1; }, equal_i => sub { my $rv = equal_i (@list) ?1:0; 1; }, equal_i2 => sub { my $rv = equal_i2(@list) ?1:0; 1; }, });
Rate equal_pm equal_i equal_i2 equal_pm 17854/s -- -51% -74% equal_i 36454/s 104% -- -46% equal_i2 67523/s 278% 85% --

In reply to Re^2: Testing the Uniformity of an Array by its Elements by ikegami
in thread Testing the Uniformity of an Array by its Elements by neversaint

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.