On Wed, Jul 22, 2009 at 12:11, Bryan R
Harris<bryan_r_har...@raytheon.com> wrote:
snip
> If your arrays could be very large, it's a waste of cycles to sort the list
> then throw most of that effort away.  You could do:
snip

Due to the fact that sort is written in C, it can be faster to sort
than to loop over the array in Perl.  I remember the value as being
around 250, but there is no need to count on memory, just benchmark:

sort => z
maxstr => z
loop => z

for a list of 10 items:
            Rate   loop   sort maxstr
loop    378300/s     --   -37%   -71%
sort    601510/s    59%     --   -54%
maxstr 1310719/s   246%   118%     --

for a list of 100 items:
           Rate   sort   loop maxstr
sort    34909/s     --   -44%   -81%
loop    61837/s    77%     --   -66%
maxstr 183991/s   427%   198%     --

for a list of 200 items:
          Rate   sort   loop maxstr
sort   14628/s     --   -56%   -85%
loop   33185/s   127%     --   -65%
maxstr 94575/s   547%   185%     --

It looks like my memory is wrong, (or there is a difference between
5.6 and 5.10).  For this you can see that it is always better to use
the List::Util's versions (about an order of magnitude better).  This
is the code that generated the benchmark:

#!/usr/bin/perl

use strict;
use warnings;

use List::Util qw/maxstr/;
use Benchmark;

sub random_strs {
        my $n = shift;
        return map { ("a" .. "z")[rand 26] } 1 .. $n;
}

my @a = random_strs 10;

my %subs = (
        loop   => sub {
                my $max = $a[0];
                for my $val (@a) {
                        $max = $val if $max lt $val;
                }
                return $max;
        },
        maxstr => sub {
                return maxstr(@a);
        },
        sort   => sub {
                return +(sort @a)[-1];
        },
);

for my $sub (keys %subs) {
        print "$sub => ", $subs{$sub}->(), "\n";
}

for my $n (10, 100, 200) {
        @a =  random_strs $n;
        print "\nfor a list of $n items:\n";
        Benchmark::cmpthese -1, \%subs;
}



-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to