On Wed, Mar 28, 2001 at 09:13:01AM -0500, Mark-Jason Dominus wrote:
> 
> > So you can say
> > 
> >   use Memoize;
> >   # ...
> >   memoize 'f';
> >   @sorted = sort { my_compare(f($a),f($b)) } @unsorted
> > 
> > to get a lot of the effect of the S word.
> 
> Yes, and of course the inline version of this technique is also
> common:
> 
>    @sorted = sort { my $ac = $cache{$a} ||= f($a);
>                     my $bc = $cache{$b} ||= f($b);
>                     my_compare($ac,$bc);
>                   } @unsorted;
> 
> Joseph Hall calls this the 'Orcish Maneuver'.

That does have the (slight) disadvantage that if f(x) returns
a false value then f(x) may be called multiple times. Of course
this can be fixed by using exists. It also has the overhead of
computing the hash value of a and b on every itteration

Personally I have found the fastest sort tends to be

  my @f = map { f($_) } @unsorted;
  @sorted = @unsorted[ sort { $f[$a] cmp $f[$b] } 0..$#f ];

Graham.

Reply via email to