I tried your benchmark and I also see map is faster. When I changed subs to return concatenated results, for loop becomes faster. I wonder why?
#!/usr/bin/perl
use strict; use warnings;
use Benchmark qw/cmpthese/;
my %h = map {$_ => $_} 1 .. 10000;
sub test1{
my $buff='';
foreach my $key (sort keys %h) {
$buff.="$key: $h{$key}\n";
}
return $buff;
}
sub test2{
return join('', map "$_: $h{$_}\n", sort keys %h);
}
print test1() eq test2() ? "same\n" : "not same\n";
my %tests = (
'01_for' => \&test1,
'02_map' => \&test2,
);
cmpthese(
-10, #for 10 cpu secs
\%tests
);
__DATA__
Rate 02_map 01_for
02_map 33.9/s -- -16%
01_for 40.2/s 19% --
update:
I remember previous thread.
"for loop" consumes lots of memory compared to while loop.
-
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.
|