Although this seems like the eternal question, as there are
many variations on this problem posted on PM,
some of which
include Benchmarks, I've just
found something a little curious when it comes to benchmarking
two approaches to this.
I'm converting a 2xn array reference, which is the result
of a DBI call (
selectall_arrayref), into a
hashref. At first, I thought the easy way might be to do
something like:
sub AssembleByHash
{
my ($array_ref) = @_;
my (%result);
foreach my $row (@$array_ref)
{
$result{$row->[0]} = $row->[1];
}
return \%result;
}
Which I thought would be far to easy, since it didn't harness
the
Power of Map. So, instead, I supposed
that this might be faster:
sub AssembleByArray
{
my ($array_ref) = @_;
my (%result);
%result = map { @$_ } @$array_ref;
return \%result;
}
After all, it's quick and to the point. When applying
Benchmark to validate my theory, though, I got the
following result using a 10_000 row test-table and 100
iterations:
Benchmark: timing 10 iterations of AssembleByArray, AssembleByHash...
AssembleByArray: 10 wallclock secs ( 9.64 usr + 0.04 sys = 9.68 CPU)
+ @ 1.03/s (n=10)
AssembleByHash: 1 wallclock secs ( 1.31 usr + 0.00 sys = 1.31 CPU)
+@ 7.63/s (n=10)
Rate AssembleByArray AssembleByHash
AssembleByArray 1.03/s -- -86%
AssembleByHash 7.63/s 639% --
So, I can only suppose that the temporary array created
by the
map call is killing performance. Or,
am I missing something?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.