What's the fastest way to code up a given task in perl?
Because Perl so lends itself to a variety of different approaches
for any given task, a common question is which is the fastest way
to code a given task. Since some approaches can be dramatically
more efficient that others, it's sometimes worth knowing which is
best. Unfortunately, the implementation that first comes to mind,
perhaps as a direct translation from C or the shell, often yields
suboptimal performance. Not all approaches have the same results
across different hardware and software platforms. Furthermore,
legibility must sometimes be sacrificed for speed.
While an experienced perl programmer can sometimes eye-ball the code
and make an educated guess regarding which way would be fastest,
surprises can still occur. So, in the spirit of perl programming
being an empirical science, the best way to find out which of several
different methods runs the fastest is simply to code them all up and
time them. For example:
$COUNT = 10_000; $| = 1;
print "method 1: ";
($u, $s) = times;
for ($i = 0; $i < $COUNT; $i++) {
# code for method 1
}
($nu, $ns) = times;
printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
print "method 2: ";
($u, $s) = times;
for ($i = 0; $i < $COUNT; $i++) {
# code for method 2
}
($nu, $ns) = times;
printf "%8.4fu %8.4fs\n", ($nu - $u), ($ns - $s);
For more specific tips, see the section on Efficiency in the
``Other Oddments'' chapter at the end of the Camel Book.