An undefined value is converted to an empty string in string context. So the two are functionally equivalent, even if one is potentially confusing.
The benchmark you wrote is not a good test because the concatenation time will be lost in the overhead for the function call. To some degree, you could argue that means, by definition, that it doesn't matter which you pick; however, if you are going to test, you should test the right thing.
#!perl
use strict;
use warnings;
use Benchmark;
my $s1 .= 'Peter geht nach Hause geht';
my $s2 = 'Peter nach Hause geht';
## Method number one - a numeric sort
sub test_concat {
my $string = shift;
my $s1x;
for (1 .. 100000) {
$s1x .= $string;
undef $s1x;
}
return $s1x;
}
## Method number two - an alphabetic sort
sub test_normal {
my $string = shift;
my $s1x;
for (1 .. 100000) {
$s1x = $string;
undef $s1x;
}
return $s1x;
}
## We'll test each one, with simple labels
my $count = 100;
timethese (
$count,
{
'Method One' => sub{ test_concat($s1); },
'Method Two' => sub{ test_normal($s1); },
}
);
exit(0);
which yields
Benchmark: timing 100 iterations of Method One, Method Two...
Method One: 4 wallclock secs ( 3.40 usr + 0.00 sys = 3.40 CPU) @ 29
+.40/s (n=100)
Method Two: 3 wallclock secs ( 3.59 usr + 0.00 sys = 3.59 CPU) @ 27
+.87/s (n=100)
or
Benchmark: timing 100 iterations of Method One, Method Two...
Method One: 3 wallclock secs ( 3.37 usr + 0.00 sys = 3.37 CPU) @ 29
+.68/s (n=100)
Method Two: 4 wallclock secs ( 3.49 usr + 0.00 sys = 3.49 CPU) @ 28
+.61/s (n=100)
or
Benchmark: timing 100 iterations of Method One, Method Two...
Method One: 4 wallclock secs ( 3.45 usr + 0.00 sys = 3.45 CPU) @ 29
+.00/s (n=100)
Method Two: 3 wallclock secs ( 3.49 usr + 0.00 sys = 3.49 CPU) @ 28
+.62/s (n=100)
So I would conclude that skipping the no-op would save me on the order 1 second for every 10 million assignments. Whether this matters for your use case depends on your use case. It would not matter for any of mine.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.