in reply to Re: Testing the Uniformity of an Array by its Elements
in thread Testing the Uniformity of an Array by its Elements
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% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Testing the Uniformity of an Array by its Elements
by tirwhan (Abbot) on Nov 02, 2005 at 17:54 UTC |