I'm not sure I completely agree. The 'x' operator still has to perform a conditional evaluation at a lower level, and 'abs' will certainly chew up some time. Here's what I get when I benchmark it:
Program 'benchmark.pl':
#!/usr/bin/perl -w
# Strict
use strict;
use warnings;
# User-defined
my $niter = 2000000;
# Libraries
use Benchmark;
# Main program
timethis($niter, \&sub1);
timethis($niter, \&sub2);
# Subroutines
sub sub1() {
my $noun = 'iteration';
for my $count (0..2) {
my $declension = 's' x (abs($count) != 1);
my $result = sprintf "$count $noun$declension so far...\n";
}
}
sub sub2() {
for my $count (0..2) {
my $s = (1 == $count)? "": "s";
my $result = sprintf "$count iteration$s so far...\n";
}
}
Results:
[liverpole@diamond<28>]% benchmark.pl
timethis 2000000: 25 wallclock secs (20.27 usr + 0.05 sys = 20.32 CPU
+) @ 98425.20/s (n=2000000)
timethis 2000000: 19 wallclock secs (17.12 usr + 0.01 sys = 17.13 CPU
+) @ 116754.23/s (n=2000000)
Of course, I had to change "print" statements to "sprintf", since the program will be ridiculously I/O-bound otherwise. But since I had to resort to an absurd iteration count anyway, it probably doesn't matter which you use for most cases.
Hey, I love your idea about a Perlmonks "habits & practices" section! If something like that existed, I would reference it all the time.
|