Well, it all depends on what you do with the results. Consider the following benchmark code:
use strict;
use warnings;
use Benchmark qw(cmpthese);
my @source = 1 .. 1000000;
my @result = @source;
cmpthese (-3,
{
for => '@result = test_for ()',
map => '@result = test_map ()',
mapf => '@result = test_mapf ()',
forv => 'test_for ()',
mapv => 'test_mapf ()',
});
sub test_for {
my @sqrt_results;
for my $result (@source) {
push @sqrt_results , sqrt($result);
}
return @sqrt_results;
}
sub test_map {
return my @sqrt_results = map { sqrt $_ } @source;
}
sub test_mapf {
return map { sqrt $_ } @source;
}
Prints:
Rate map for mapf forv mapv
map 2.24/s -- -3% -31% -49% -78%
for 2.31/s 3% -- -29% -48% -77%
mapf 3.27/s 46% 41% -- -26% -68%
forv 4.43/s 98% 92% 36% -- -56%
mapv 10.1/s 353% 339% 210% 129% --
Update: and for about 100,000 or fewer elements percentages are:
Rate for map mapf forv mapv
for 23849/s -- -3% -29% -46% -76%
map 24506/s 3% -- -27% -45% -76%
mapf 33666/s 41% 37% -- -24% -66%
forv 44571/s 87% 82% 32% -- -56%
mapv 100159/s 320% 309% 198% 125% --
In this case for my @source = 1 .. 100;, but the percentages are very much the same over a wide range of elements.
Perl reduces
RSI - it saves typing
-
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.