Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

I thought you might say that (and by "you", I mean "somebody").

use Benchmark qw( cmpthese ); use List::Util qw( shuffle ); my @set = shuffle 1 .. 1_000_000; cmpthese( 100, { 'sort' => sub { my @x = sort { $b <=> $a } @set; return; } +, 'rsort' => sub { my @x = reverse sort { $a <=> $b } @set; +return; }, } ); __END__ Rate sort rsort sort 1.01/s -- -2% rsort 1.03/s 2% --

(As I recall, 2% is within the margin of error for Benchmark.)

In perl (the implementation of Perl), there's a special case for reverse sort so that it doesn't have the performance penalty you might otherwise expect it to have. That being the case, the main difference between reverse sort { $a cmp $b } and sort { $b cmp $a } is how they read to the programmer. I think that it's far more obvious what's going on when you reverse sort especially as the expressions involved become more complicated. It could be pretty easy to lose the $a and $b in a big block. Even if it were not optimized, I think you'd have to have a pretty long list before the performance penalty outweighs the maintainability benefit.

This also means there's no performance penalty for reverse sort { $b <=> $a }, but that's just rude.


In reply to Re^3: Sorting keys of hash table by values by kyle
in thread Sorting keys of hash table by values by iman_saleh

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2024-04-24 22:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found