On 2/20/06, John W. Krahn <[EMAIL PROTECTED]> wrote: snip > my ( $smallestNum, $largestNum ) = ( sort { $a <=> $b } @numbers )[ 0, -1 ]; > > Although as I said, the for loop is more efficient. snip
Ah this old chestnut. Depending on the size of the array sort is faster (after 200 or so items for starts to be better). See the benchmark program at the end of the post for how these numbers were generated. Results for list of 10 items Rate for sort for 146391/s -- -57% sort 338736/s 131% -- Results for list of 20 items Rate for sort for 101629/s -- -51% sort 205937/s 103% -- Results for list of 40 items Rate for sort for 57833/s -- -39% sort 95050/s 64% -- Results for list of 80 items Rate for sort for 32950/s -- -22% sort 42259/s 28% -- Results for list of 160 items Rate for sort for 17379/s -- -7% sort 18656/s 7% -- Results for list of 320 items Rate sort for sort 8281/s -- -7% for 8905/s 8% -- #!/usr/bin/perl use strict; use Benchmark qw(cmpthese); sub min_for { my $min = shift; for (@_) { $min = $_ if $_ < $min; } return $min; } sub min_sort { (sort { $a <=> $b } @_)[0] } for my $size (10, 20, 40, 80, 160, 320) { my @rand; push @rand, rand(1000) for 1 .. $size; print "Results for list of $size items\n"; cmpthese( -3, { 'for' => sub { min_for(@rand) }, 'sort' => sub { min_sort(@rand) } }, ); print "\n"; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>