Wow! Using a Schwartz Transform to sort a hash by value is like using a sledgehammer to crack open a peanut. The ST is not cheap, it only wins when the cost of computing the key is relatively expensive, and accessing a hash value by key is one of the cheaper things you can do in Perl. I wonder just how much slower this is?

# /usr/bin/perl -w use strict; use Benchmark qw/cmpthese/; cmpthese( shift || 10_000, { 'sort' => sub { sort keys %ENV }, 'sort by key' => sub { sort {$ENV{$a} cmp $ENV{$b}} keys %ENV }, 'sort by ST' => sub { map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, $ENV{$_}] } keys %ENV }, }); __END__ % perl -w sortem 100000 Benchmark: timing 100000 iterations of sort, sort by ST, sort by key.. +. sort: 2 wallclock secs ( 1.35 usr + 0.00 sys = 1.35 CPU) @ 73 +964.50/s (n=100000) sort by ST: 18 wallclock secs (17.72 usr + 0.00 sys = 17.72 CPU) @ 56 +44.62/s (n=100000) sort by key: 2 wallclock secs ( 1.34 usr + 0.00 sys = 1.34 CPU) @ 7 +4515.65/s (n=100000) Rate sort by ST sort sort by key sort by ST 5645/s -- -92% -92% sort 73964/s 1210% -- -1% sort by key 74516/s 1220% 1% --

Yep, pretty slow! (I threw the straight sort in there as well, just to give an idea of the overhead incurred by using a sort code block).


print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'

In reply to Re:x2 Sorting by the hash value by grinder
in thread Sorting by the hash value by Anonymous Monk

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.