I use various internal and external APIs to build my services. An external API returns content something like below:
{
"status": 1,
"error_msg": '',
"result": {
"foo1": { .... },
"foo2": { .... },
"foo3": { .... },
"foo4": { .... }
}
}
After retrieving this, I have to sort the result in result.foo1, result.foo2, ..., result.foo100 order. I'm wondering why they don't return this in array, but I must face it as long as the provider is returning values in this way. Although
Perl Best Practices insists on using
Sort::Maker, I implemented this in my way because this sort wasn't that complicated.
my %tmp_cache; # for orcish maneuver
my @sorted_keys = sort {
( $tmp_cache{$a} //= $a =~ s/\A foo(\d+) \z/$1/xr ) <=>
( $tmp_cache{$b} //= $b =~ s/\A foo(\d+) \z/$1/xr )
} keys %{ $content->{result} };
# then sorted results are stored in stash to be displayed
$c->stash->{results} = [ map { $content->{result}->{$_} } @sorted_keys ];
Today, I benchmarked each sort type provided by Sort::Maker and found that using Sort::Maker was much faster. The code is as below. It was a bit surprising that my original method with orcish maneuver is13% slower than Sort::Maker's one with orcish maneuver. Needless to say, other sort types are much faster. So my conclusion is that even relatively simple sort should be implemented with Sort::Maker to increase readability, maintenancibility and performance.