[Omaha.pm] Sort quickie

Hugh Jarce hjarce2001 at yahoo.com
Thu Aug 5 18:21:41 CDT 2004


Jay Hannah <jay at jays.net>:
> -ponder-  I need to study Benchmark. Looks cool. What's the point of
> @x? Can
> 
>     sub j9 { my @x = sort by_date @dates }
> 
> be written as
> 
>     sub j9 { sort by_date @dates }
> ?

No. Benchmark calls the subs in scalar context; the my @x is used to
force sort to be called in list context. As for what sort *should*
do in scalar context, noone is really sure -- the latest consensus
is that it should play nethack:

<http://www.nntp.perl.org/group/perl.perl5.porters/92250>
<http://www.nntp.perl.org/group/perl.perl5.porters/92477>
 
>> sub j1 {
>>     my @x = map { substr($_,4) } sort map { substr($_,4).$_ } @dates
>> }
> 
> -laugh-  Took me 3 minutes to figure out what that does. map tends to 
> confuse my limited synapses.
> 
>> Which surprised me. I expected j1 to be much faster.
> 
> Usually its faster for me to re-write a use of map than it is for me to 
> figure out what I was doing when I wrote it. -grin- Typically I can't 
> grok map at a glance, which slows me down. Can't argue w/ fast 
> benchmarking though!
> 
> Thanks for the tips!

You're welcome. Actually, I wasn't trying to be silly on purpoose
(for once), just following the standard GRT sort hack:

<http://www.perlmonks.org/index.pl?node_id=145659>

The GRT and its cousin the Schwartzian Transform are usually a lot
faster whenever the comparison function is expensive because they
pre-compute the sort keys just n times (rather than n log n when
called by sort). The GRT is usually faster than the Schwartzian
Transform because sort without a sort block or function is done
in C and so is faster than interpreting the Perl sort function.

Hugh



		
__________________________________
Do you Yahoo!?
Take Yahoo! Mail with you! Get it on your mobile phone.
http://mobile.yahoo.com/maildemo 


More information about the Omaha-pm mailing list