Something I just realized, which though it is a simple revelation, I was missing it for a while... for anyone who does
for(reverse sort @foo)
it is much faster to instead use a sort subroutine set up to return a reversed sort, i.e.
for(sort {$b <=> $a} @foo)
$b <=> $a instead of $a <=> $b returns reversed list...

and use cmp instead of <=>

My benchmars show a SIGNIFICANT difference between the two...

just something I thought I'd share... many people probably realized this already

Update HAHAHAH, I wrote this just before I left, went home and just read Nathan Torkington's article in TPJ #20 about arrays, which says the same thing I do here... That's funny in my book.
                - Ant

Replies are listed 'Best First'.
Re: reversing a sort...
by arhuman (Vicar) on May 09, 2001 at 11:08 UTC
Re: reversing a sort...
by ChemBoy (Priest) on May 09, 2001 at 01:32 UTC

    Umm... use cmp instead of <=> if you're sorting strings instead of numbers. Otherwise, do go right ahead and use <=>



    If God had meant us to fly, he would *never* have give us the railroads.
        --Michael Flanders

Re: reversing a sort...
by DrZaius (Monk) on May 09, 2001 at 01:45 UTC
    Sure, on a simple cmp sort. There is a definite knee point when your sort subroutine takes more effort than a reverse.
      Huh? I don't think your assertion makes sense. reverse sort { arbitrary code } @list will always be less efficient than sort { arbitrary code with $a and $b swapped } @list.

      Whether the sort takes more time than the reverse doesn't matter, because you have to do the same sort in either case.

        He was pointing out that sort {$a cmp $b} @list is slower than sort @list because you save the overhead of calling the sort function. The difference should be big enough at some point that it is faster to reverse sort @list instead of sort {$b cmp $a} @list.

        Testing this is going to be tricky, of course, because sorting effiency depends on the order you see elements in.

        Also this is a very, very special case. With more complex sorts there is choice about how to write it either way, and reverse has to be a waste of time.

        UPDATE
        Bloody language maintainers. Going and rendering my hard-won optimization knowledge obsolete by making everything fast. Bah.

        reverse sort { arbitrary code } @list will always be less efficient than sort { arbitrary code with $a and $b swapped } @list

        Not always, the number of comparisons and swaps performed by sort will depend on the order of the list. On my machine, reverse sort {$a <=> $b} (1..100000); is faster than sort {$b <=> $a} (1..100000);

        For almost all cases, you are correct, but it is not _always_ the case.