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' | [reply] [d/l] |
| [reply] |