The following code strives to test only chop, chomp, and a noop for the same number of iterations, with the same starting data on each iteration. As far as is practical it attempts to maintain simplicity and to establish a control group (mynada) that performs as similar an algorithm as possible to the two other alternatives. Observe this code and the results:
use strict;
use warnings;
use Benchmark qw(cmpthese);
my @orig = ("\n") x 100000;
sub mychomp {
my $data = shift;
my @copy = @$data;
chomp for @copy;
}
sub mychop {
my $data = shift;
my @copy = @$data;
chop for @copy;
}
sub mynada {
my $data = shift;
my @copy = @$data;
1 for @copy;
}
cmpthese -10, {
chomp => sub {mychomp(\@orig)},
chop => sub {mychop(\@orig)},
nada => sub {mynada(\@orig)},
};
This produces (on my system):
Rate chomp chop nada
chomp 87.8/s -- -4% -20%
chop 91.6/s 4% -- -16%
nada 109/s 25% 20% --
This shows me that the noop is about 20%-25% faster than the other two alternatives, and that the other two are only 4% apart, which is really within the margin for error.
The fact that you are getting more dramatically different results might indicate that the experiment is not as pristine as it should be, and that you are comparing non-equivalent alternatives.
-
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.