No, this is quite efficient. Hash accesses are very fast.
But if you really think you need every cycle, you might try the following
use warnings;
use strict;
my %hash= ('a' => {'Size' => 40 },
'b' => {'Size' => 3000 },
'c' => {'Size' => 20 },
'd' => {'Size' => 1 },
'e' => {'Size' => 12 }
);
my @unsort= map ( $hash{$_}->{"Size"} .':' . $_ , keys %hash);
no warnings;
my @sort= sort {$a<=>$b } @unsort;
use warnings;
foreach (@sort) {
s/[^:]*://;
}
print join' ',@sort,"\n";
# prints
d e c a b
You really should test whether you get any speedup through this, you need fairly large hashes to see any difference at all, as you trade two hash accesses for two string-to-int conversions per sort operation. I'm not sure what will win
Instead of turning off the warnings you could also normalize the size numbers for the sorting by putting '0' before each number so that all numbers are the same size and extract the numbers in the sort routine, but that will definitely eat up any speedup over your original sort
UDPATE: Yes, forgot the Schwarzian Transform, again.
|