On 9/10/07, Jeremy Kister <[EMAIL PROTECTED]> wrote: > I am trying to optimize some sorting code I have. The data structure is > as follows: > > my %hash = (x => [ 'a','b','c' ], > y => [ 'd','e' ], > z => [ 'f' ], > ); > > > The result I expect is simply the highest number of elements. In this > case, the result should be "3" because x has three elements, which is > more than y and z have. > > > I whipped up two versions of the sort code: > > foreach my $key (keys %hash){ > if(@{$hash{$key}} > $highest){ > $most = @{$hash{$key}}; > } > } > > > #and > > my $most = @{$hash{(sort { @{$hash{$b}} <=> @{$hash{$a}} } keys %hash)[0]}}; > > > > I ran each 500,000 times. I expected the second version finish sooner, > but it is noticeably slower than the first. > > Can someone show me a better way to get this done ? snip
The problem is that you aren't sorting an array or a list, you are sorting a transform ed list. The Perl loop is faster because it performs the transform only once for each element. If fact, the transform costs significantly more than the comparison. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/