Example 13-9. benchmarks/join_long.pl
use Benchmark;
use Symbol;
my $fh = gensym;
open $fh, ">/dev/null" or die;
my($one, $two, $three, $four) = map { $_ x 1000 } ('a'..'d');
timethese(500_000, {
interp => sub {
print $fh "$one$two$three$four";
},
list => sub {
print $fh $one, $two, $three, $four;
},
conc => sub {
print $fh $one . $two . $three . $four;
},
});
Here's the benchmarking result:
Benchmark: timing 500000 iterations of interp, list...
conc: 5 wallclock secs ( 4.47 usr + 0.27 sys = 4.74 CPU)
interp: 4 wallclock secs ( 4.25 usr + 0.26 sys = 4.51 CPU)
list: 4 wallclock secs ( 2.87 usr + 0.16 sys = 3.03 CPU)
In this case using a list is about 30% faster than interpolation.
Concatenation is a little bit slower than interpolation.
Let's look at this code:
$title = 'My Web Page';
print "<h1>$title</h1>"; # Interpolation (slow)
print '<h1>' . $title . '</h1>'; # Concatenation (slow)
print '<h1>', $title, '</h1>'; # List (fast for long strings)
When you use "<h1>$title</h1>", Perl
does interpolation (since "" is an operator in
Perl)—it parses the contents of the string and replaces any
variables or expressions it finds with their respective values. This
uses more memory and is slower than using a list. Of course, if there
are no variables to interpolate it makes no difference whether you
use "string" or 'string'.
Concatenation is also potentially slow, since Perl might create a
temporary string, which it then prints.
Example 13-10. size_interp.pl
$uri = '/test';
$filename = '/test.pl';
print "uri => ", $uri, " filename => ", $filename, "\n";
print "uri => " . $uri . " filename => " . $filename . "\n";
print "uri => $uri filename => $filename\n";
1; # needed for TerseSize to report the previous line's size
Let's look at how many bytes each line compiles
into. We will use B::TerseSize for this purpose:
panic% perl -MO=TerseSize size_interp.pl | grep line
size_interp.pl syntax OK
[line 1 size: 238 bytes]
[line 2 size: 241 bytes]
[line 3 size: 508 bytes]
[line 4 size: 636 bytes]
[line 5 size: 689 bytes]
The code in line 3, which uses a list of arguments to print(
), uses significantly less memory (508 bytes) than the code
in line 4, which uses concatenation (636 bytes), and the code in line
5, which uses interpolation (689 bytes).